在Ninject依赖关系解析期间如何获取实现类型? [英] How to get implementing type during Ninject dependency resolve?

查看:66
本文介绍了在Ninject依赖关系解析期间如何获取实现类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Log4net进行日志记录,并且我有很多具有ILog依赖项的对象.这些依赖项与其他依赖项一样被注入.我想遵循Log4net记录器的命名约定,以便以实例的类型命名注入到实例的记录器.我一直在为ILog使用以下绑定:

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
}

我尝试了几种方法来从ctx获取实现类型,但均未成功.有什么方法可以获取实现类型?

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?

推荐答案

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));

因此,context.Request.ParentContext.Plan.TypeILog类型的注入对象.如果您想做IResolutionRoot.Get<ILog>(),则不会有类型将ILog注入到其中,因此也就不会有ParentContext.在这种情况下,您需要像以前的解决方案一样进行null检查:

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));

这篇关于在Ninject依赖关系解析期间如何获取实现类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆