How to get implementing type during Ninject dependency resolve?

纵饮孤独 提交于 2019-12-02 21:29:48

问题


I use Log4net for logging and I have a lot of objects with an ILog dependency. These dependencies are injected just as the others. I would like to stick to the Log4net logger naming convention so the logger injected to an instance is named after the type of the instance. I have been using the following binding for ILog:

Bind<ILog>().ToMethod(ctx =>
    LogManager.GetLogger(ctx.Request.ParentRequest == null ? typeof(object) : ctx.Request.ParentRequest.Service)
);

Which is against the naming convention because loggers will be named after the interface not the implementing type.

interface IMagic {}

class Magic: IMagic
{
    ILog logger; // The logger injected here should have the name "Magic" instead of IMagic
}

I tried a couple of ways to get the implementing type from ctx with no success. Is there any way to get the implementing type?


回答1:


this and that covers your questions but they're not exactly duplicates, so i'll repost this:

Bind<ILog>().ToMethod(context =>
             LogManager.GetLogger(context.Request.ParentContext.Plan.Type));

so context.Request.ParentContext.Plan.Type is the type ILog is injected into. If you ever want to do IResolutionRoot.Get<ILog>() then there won't be a type to inject ILog into and so there won't be a ParentContext either. In that case you'll need the null check as in your previous solution:

Bind<ILog>().ToMethod(context =>
             LogManager.GetLogger(context.Request.ParentContext == null ?
                                  typeof(object) : 
                                  context.Request.ParentContext.Plan.Type));


来源:https://stackoverflow.com/questions/30457623/how-to-get-implementing-type-during-ninject-dependency-resolve

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!