Ninject传递实现接口的类的构造方法参数typeof [英] Ninject pass constructor argument typeof class that implements the interface

查看:103
本文介绍了Ninject传递实现接口的类的构造方法参数typeof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在我的应用程序日志记录包装程序中使用Ninject.

I am attempting to use Ninject with my application logging wrapper.

这是包装纸:

public class NLogLogger : ILogger
{
    private readonly Logger _logger;

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

如您所见,我正在将类型传递给loggers构造函数,因此我将使用它,如下所示:

As you can see I am passing the type into the loggers constrctor, so I would use it like the following:

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

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

现在,我似乎无法找出如何使用Ninject做类似的事情. 这是我的绑定模块:

Now I cannot seem to find out how to do something similar with using Ninject. Here is my binding module:

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

现在很明显,我抛出了异常,因为它无法将类型注入构造函数.有什么想法可以做到吗?

Now obviously I get an exception thrown because it cannot inject the type into the constructor. Any ideas how I can do this?

激活类型时出错

Error activating Type

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

No matching bindings are available, and the type is not self-bindable.

激活路径:

4)将依赖类型注入到NLogLogger类型的构造函数的参数t中

4) Injection of dependency Type into parameter t of constructor of type NLogLogger

3)将依赖项ILogger注入到NzbGetSettingsService类型的构造函数的参数记录器中

3) Injection of dependency ILogger into parameter logger of constructor of type NzbGetSettingsService

2)将依赖项ISettingsService {NzbGetSettingsDto}注入DashboardController类型的构造函数的参数nzbGetService

2) Injection of dependency ISettingsService{NzbGetSettingsDto} into parameter nzbGetService of constructor of type DashboardController

1)请求DashboardController

1) Request for DashboardController

推荐答案

假设您的类如下所示:

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

这篇关于Ninject传递实现接口的类的构造方法参数typeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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