Simple Injector:使用基于其父级的构造函数参数注册类型

The*_*ads 15 c# dependency-injection ioc-container simple-injector

我目前正在从我的项目中删除Ninject,并转向使用Simple Injector,但有一件事我无法正常工作.

对于我的日志记录,在注册服务时,我之前能够将参数传递到我的日志记录类中

_kernel.Bind<ILogger>().To<Logger>()
    .WithConstructorArgument("name",
        x => x.Request.ParentContext.Request.Service.FullName);
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种在Simple Injector中重新创建它的方法.到目前为止,我还有其他一切工作但是这个.我可以通过执行以下操作来使日志记录正常工作,尽管没有显示正确的记录器名称:

_container.Register<ILogger>(() => new Logger("test"));
Run Code Online (Sandbox Code Playgroud)

做任何类似事情的人都有经验吗?

Ste*_*ven 11

该注册是一种基于上下文的注入形式.您可以使用其中一个RegisterConditional重载.

RegisterConditional但是不允许使用工厂方法来构造类型.因此,您应该创建类的通用版本Logger,如下所示:

public class Logger<T> : Logger
{
    public Logger() : base(typeof(T).FullName) { }
}
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式注册:

container.RegisterConditional(
    typeof(ILogger),
    c => typeof(Logger<>).MakeGenericType(c.Consumer.ImplementationType),
    Lifestyle.Transient,
    c => true);
Run Code Online (Sandbox Code Playgroud)

但是,如果您没有记录太多,请阅读此Stackoverflow问题(以及我的回答)并自问.


Tim*_*ver 5

现在,通过使用该RegisterConditional方法,Simple Injector 3支持基于上下文的注入.例如,要将Logger注入Consumer1,将Logger注入Consumer2,请使用接受实现类型工厂委托的RegisterConditional重载,如下所示:

container.RegisterConditional(
    typeof(ILogger),
    c => typeof(Logger<>).MakeGenericType(c.Consumer.ImplementationType),
    Lifestyle.Transient,
    c => true);
Run Code Online (Sandbox Code Playgroud)