2015-11-18 124 views
2

我正在尝试使用Ninject与我的应用程序日志包装。Ninject通过构造函数参数typeof类实现接口

这里是包装:

public class NLogLogger : ILogger 
{ 
    private readonly Logger _logger; 

    public NLogLogger(Type t) 
    { 
     _logger = LogManager.GetLogger(t.Name); 
    } 
} 

正如你可以看到我传递的类型分为伐木者constrctor,所以我会用它像下面这样:

public class EntityObject 
{ 
    public ILogger Logger { get; set; } 

    public EntityObject() 
    { 
     Logger = new NLogLogger(typeof(EntityObject)); 
    } 
} 

现在我似乎无法了解如何使用Ninject做类似的事情。 这里是我的绑定模块:

public class LoggerModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<ILogger>().To<NLogLogger>(); 
    } 
} 

现在很明显,我得到抛出,因为它不能注入类型到构造异常。任何想法我可以做到这一点?

错误激活类型

没有匹配的绑定是可用的,并且类型不是自可绑定。

激活路径:

4)依赖型注射入NLogLogger型的构造的参数t

3)依赖ILogger注射到型NzbGetSettingsService

2)射出的构造的参数记录器依赖关系ISettingsService {NzbGetSettingsDto}转换为DashboardController类型的构造函数的参数nzbGetService

1)请求DashboardController

回答

2

假设你的类是这样的:

public class EntityObject 
{ 
    public ILogger Logger { get; set; } //it is better by the way to convert this into a private field 

    public EntityObject(ILogger logger) 
    { 
     Logger = logger; 
    } 
} 

您需要注册您的NLogLogger这样的:

Bind<ILogger>().To<NLogLogger>() 
    .WithConstructorArgument(
     typeof(Type), 
     x => x.Request.ParentContext.Plan.Type); 
+0

真棒,谢谢。我一直在拉我的头发! –