Ninject 传递实现接口的构造函数参数 typeof class

Ninject pass constructor argument typeof class that implements the interface

我正在尝试将 Ninject 与我的应用程序日志包装器一起使用。

这是包装纸:

public class NLogLogger : ILogger
{
    private readonly Logger _logger;

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

如您所见,我将类型传递给记录器构造函数,因此我将按如下方式使用它:

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

现在显然我抛出了一个异常,因为它无法将类型注入构造函数。我有什么想法可以做到这一点吗?

Error activating Type

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

Activation path:

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

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

2) Injection of dependency ISettingsService{NzbGetSettingsDto} into parameter nzbGetService of constructor of type 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);