Simple Injector:在基类中注入属性

Smi*_*tha 4 .net c# dependency-injection ioc-container simple-injector

几周以来,我一直在使用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)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我的配置现在看起来像这样:

container.Register<HandlerContext, AspHandlerContext>();
container.Register<Handler<NotifyCustomerMessage>, NotifyCustomerHandler>();
// many other Handler<T> lines here
Run Code Online (Sandbox Code Playgroud)

如何在BaseHandler中注入属性?

在此先感谢您的帮助.

Ste*_*ven 9

关于属性注入的Simple Injector 文档给出了非常明确的解释.基本选项是:

  • 使用注册初始化委托RegisterInitializer.
  • 覆盖简单注入器PropertySelectionBehavior.

正如文档所解释的那样,RegisterInitializer不建议使用依赖项的属性注入; 仅适用于配置值.

这使您可以覆盖Simple Injector PropertySelectionBehavior,但是基类本身就像SOLID违规一样.请看下面的文章.它描述了为什么有一个基类可能是一个坏主意,本文提出了一个解决方案.