简体   繁体   English

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

[英]Simple Injector: Registering a type with constructor argument that's based on its parent

I am currently in the process of removing Ninject from my project, and moving to using Simple Injector but there is one thing that I can not get working properly. 我目前正在从我的项目中删除Ninject,并转向使用Simple Injector,但有一件事我无法正常工作。

For my logging, in the registering of services, I was previously able to pass in a parameter into my logging class as such 对于我的日志记录,在注册服务时,我之前能够将参数传递到我的日志记录类中

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

I am looking for a way to recreate this in Simple Injector. 我正在寻找一种在Simple Injector中重新创建它的方法。 So far I have everything else working but this. 到目前为止,我还有其他一切工作但是这个。 I can get the logging to work, albeit without having the correct logger names being shown, by doing the following: 我可以通过执行以下操作来使日志记录正常工作,尽管没有显示正确的记录器名称:

_container.Register<ILogger>(() => new Logger("test"));

Anyone got any experience in doing anything similar? 做任何类似事情的人都有经验吗?

That registration is a form of context based injection . 该注册是一种基于上下文的注入形式。 You can use one of the RegisterConditional overloads for this. 您可以使用RegisterConditional重载之一。

RegisterConditional however does not allow the use of factory methods to construct a type. 但是RegisterConditional不允许使用工厂方法来构造类型。 So you should create a generic version of your Logger class, as follows: 因此,您应该创建Logger类的通用版本,如下所示:

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. 但是,如果您没有记录太多,请阅读此Stackoverflow问题 (以及我的回答)并自问。

Context based injection is now supported in Simple Injector 3 by using the RegisterConditional method. 现在,通过使用RegisterConditional方法,Simple Injector 3支持基于上下文的注入 For example to inject a Logger into Consumer1 and a Logger into Consumer2, use the RegisterConditional overload that accepts a implementation type factory delegate as follows: 例如,要将Logger注入Consumer1,将Logger注入Consumer2,请使用接受实现类型工厂委托的RegisterConditional重载,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM