[英]Simple Injector: Injecting a property in a base class
For several weeks I've been using the Simple Injector dependency injection container, with great success.几个星期以来,我一直在使用Simple Injector依赖注入容器,并取得了巨大的成功。 I love the easy by which I can configure it.
我喜欢轻松配置它。 But now I have a design that I don't know how to configure.
但是现在我有一个我不知道如何配置的设计。 I have a base class where many types from derive, and I want to inject a dependency into a property of the base class, but without having to configure that for every derived class.
我有一个基础 class,其中有许多类型来自派生,我想将依赖项注入到基础 class 的属性中,但不必为每个派生的 class 配置它。 I tried to do this with attributes, but Simple Injector does not support attributes.
我试图用属性来做到这一点,但 Simple Injector 不支持属性。 Here is a trimmed down version of my design.
这是我设计的精简版。
public interface Handler<TMessage> where TMessage : Message
{
void Handle(TMessage message);
}
public abstract class BaseHandler
{
// This property I want to inject
public HandlerContext Context { get; set; }
}
// Derived type
public class NotifyCustomerHandler : BaseHandler,
Handler<NotifyCustomerMessage>
{
public NotifyCustomerHandler(SomeDependency dependency)
{
}
public void Handle(NotifyCustomerMessage message)
{
}
}
My configuration now looks like this:我的配置现在看起来像这样:
container.Register<HandlerContext, AspHandlerContext>();
container.Register<Handler<NotifyCustomerMessage>, NotifyCustomerHandler>();
// many other Handler<T> lines here
How can I inject the property in the BaseHandler?如何在 BaseHandler 中注入属性?
Thanks in advance for any help.提前感谢您的帮助。
The Simple Injector documentation on property injection gives a very clear explanation about this. 关于属性注入的 Simple Injector 文档对此给出了非常清晰的解释。 The basic options are:
基本选项是:
RegisterInitializer
.RegisterInitializer
注册初始化委托。PropertySelectionBehavior
.PropertySelectionBehavior
。 As the documentation explains, the use of RegisterInitializer
is not advised for property injection on dependencies;正如文档所解释的,不建议使用
RegisterInitializer
对依赖项进行属性注入; only on configuration values.仅在配置值上。
This leaves you with overriding Simple Injector's PropertySelectionBehavior
, but having a base class by itself smells like a SOLID violation.这使您可以覆盖 Simple Injector 的
PropertySelectionBehavior
,但是拥有一个基础 class 本身就闻起来像是违反了 SOLID 规定。 Please take a look at the following article .请看下面的文章。 It describes why having a base class might be a bad idea and the article presents a solution for this.
它描述了为什么拥有一个基础 class 可能是一个坏主意,并且文章为此提供了一个解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.