gpt4 book ai didi

c# - Ninject 传递实现接口(interface)的构造函数参数 typeof 类

转载 作者:行者123 更新时间:2023-11-30 23:33:44 36 4
gpt4 key购买 nike

我正在尝试将 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 做类似的事情。这是我的绑定(bind)模块:

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

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

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

关于c# - Ninject 传递实现接口(interface)的构造函数参数 typeof 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33790832/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com