几周以来,我一直在使用Simple Injector依赖注入容器,取得了巨大的成功。我喜欢简单的配置它。但现在我有一个我不知道如何配置的设计。我有一个基类,其中派生了许多类型,我想将依赖注入基类的属性,但不必为每个派生类配置。我尝试使用属性执行此操作,但Simple Injector不支持属性。这是我设计的精简版。
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)
{
}
}
我的配置现在看起来像这样:
container.Register<HandlerContext, AspHandlerContext>();
container.Register<Handler<NotifyCustomerMessage>, NotifyCustomerHandler>();
// many other Handler<T> lines here
如何在BaseHandler中注入属性?
提前感谢您的帮助。
答案 0 :(得分:9)
简单注射器documentation on property injection给出了非常明确的解释。基本选项是:
RegisterInitializer
注册初始化委托。PropertySelectionBehavior
。正如文档所解释的那样,不建议使用RegisterInitializer
来依赖属性注入;仅限于配置值。
这使您可以覆盖Simple Injector的PropertySelectionBehavior
,但是基类本身就像SOLID违规一样。请看the following article。它描述了为什么有一个基类可能是一个坏主意,本文提出了一个解决方案。