几个星期以来我一直在使用简易注射器 https://simpleinjector.org依赖注入容器,取得了巨大成功。我喜欢它的简单配置。但现在我有一个设计,我不知道如何配置。我有一个基类,其中派生出许多类型,并且我想将依赖项注入到基类的属性中,但不必为每个派生类进行配置。我尝试使用属性来做到这一点,但简单注入器不支持属性。这是我的设计的精简版本。
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 中注入该属性?
预先感谢您的任何帮助。
简单的注射器财产注入文件 https://simpleinjector.readthedocs.io/en/latest/advanced.html#property-injection对此给出了非常明确的解释。基本选项是:
- 使用注册初始化委托
RegisterInitializer
.
- 覆盖简单注入器
PropertySelectionBehavior
.
正如文档所解释的,使用RegisterInitializer
不建议对依赖项进行属性注入;仅针对配置值。
这给你留下了覆盖简单注入器的PropertySelectionBehavior
,但是拥有一个基类本身就听起来像是一种严重的违规。请看一下下面的文章 https://cuttingedge.it/blogs/steven/pivot/entry.php?id=91。它描述了为什么拥有基类可能是一个坏主意,并且本文提出了一个解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)