简单的喷油器:在基类中注入一个属性 [英] Simple Injector: Injecting a property in a base class
问题描述
有关几个星期我一直在使用href=\"https://simpleinjector.org\" rel=\"nofollow\">简单的注射器依赖注入容器,大获成功的
For several weeks I've been using the Simple Injector dependency injection container, with great success. 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. I tried to do this with attributes, but Simple Injector does not support attributes. 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
我怎么能注入在BaseHandler财产?
How can I inject the property in the BaseHandler?
在您的帮助谢谢
推荐答案
简单喷油器的物业注入文档提供了有关这是一个非常明确的解释。基本的选项是:
The Simple Injector documentation on property injection gives a very clear explanation about this. The basic options are:
- 使用注册一个初始化委托
RegisterInitializer
- 覆盖简单的喷油器的
PropertySelectionBehavior
。
- Register an initialization delegate using
RegisterInitializer
. - Override Simple Injector's
PropertySelectionBehavior
.
由于文件解释说,使用 RegisterInitializer
不建议对房地产的依赖注射;仅在配置值。
As the documentation explains, the use of RegisterInitializer
is not advised for property injection on dependencies; only on configuration values.
这让你有压倒一切的简单喷油器的 PropertySelectionBehavior
,但其本身不具有一个基类气味像一个坚实的冲突。请看看下面的文章。它描述了为什么有一个基类可能是一个坏主意,文章提出了一个解决方案。
This leaves you with overriding Simple Injector's PropertySelectionBehavior
, but having a base class by itself smells like a SOLID violation. 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.
这篇关于简单的喷油器:在基类中注入一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!