【问题标题】:Simple Injector: Injecting a property in a base class简单注入器:在基类中注入属性
【发布时间】:2011-09-07 19:08:05
【问题描述】:

几个星期以来,我一直在使用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 中注入属性?

提前感谢您的帮助。

【问题讨论】:

    标签: c# .net dependency-injection ioc-container simple-injector


    【解决方案1】:

    Simple Injector documentation on property injection 对此给出了非常清晰的解释。基本选项是:

    • 使用RegisterInitializer注册初始化委托。
    • 覆盖 Simple Injector 的 PropertySelectionBehavior

    正如文档所解释的,不建议使用RegisterInitializer 对依赖项进行属性注入;仅在配置值上。

    这让您可以覆盖 Simple Injector 的 PropertySelectionBehavior,但是拥有一个基类本身就像违反 SOLID 一样。请查看the following article。它描述了为什么拥有一个基类可能是一个坏主意,并且本文提出了一个解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多