我目前正在从我的项目中删除 Ninject,并转而使用 Simple Injector,但有一件事我无法正常工作。
对于我的日志记录,在注册服务时,我以前能够将参数传递到我的日志记录类中
_kernel.Bind<ILogger>().To<Logger>()
.WithConstructorArgument("name",
x => x.Request.ParentContext.Request.Service.FullName);
我正在寻找一种在 Simple Injector 中重新创建它的方法。到目前为止,除了这个,我还有其他所有工作。通过执行以下操作,我可以使日志记录正常工作,尽管没有显示正确的记录器名称:
_container.Register<ILogger>(() => new Logger("test"));
有没有人有做类似事情的经验?
最佳答案
该注册是一种基于上下文的注入(inject)。您可以为此使用 RegisterConditional
重载之一。
RegisterConditional
但是不允许使用工厂方法来构造类型。因此,您应该创建一个通用版本的 Logger
类,如下所示:
public class Logger<T> : Logger
{
public Logger() : base(typeof(T).FullName) { }
}
您可以通过以下方式注册:
container.RegisterConditional(
typeof(ILogger),
c => typeof(Logger<>).MakeGenericType(c.Consumer.ImplementationType),
Lifestyle.Transient,
c => true);
但请务必阅读 this Stackoverflow question (和我的回答)并问自己是否没有记录太多。
关于c# - 简易喷油器 : Registering a type with constructor argument that's based on its parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917332/