15

我目前正在从我的项目中删除 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"));

有人有做过类似事情的经验吗?

4

2 回答 2

11

That registration is a form of context based injection. You can use one of the RegisterConditional overloads for this.

RegisterConditional however does not allow the use of factory methods to construct a type. So you should create a generic version of your Logger class, as follows:

public class Logger<T> : Logger
{
    public Logger() : base(typeof(T).FullName) { }
}

You can register it as follows:

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

But please do read this Stackoverflow question (and my answer) and question yourself if you aren't logging too much.

于 2012-12-17T16:17:32.700 回答
5

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

container.RegisterConditional(
    typeof(ILogger),
    c => typeof(Logger<>).MakeGenericType(c.Consumer.ImplementationType),
    Lifestyle.Transient,
    c => true);
于 2015-10-22T13:23:24.327 回答