簡體   English   中英

簡單注入器:在基礎 class 中注入屬性

[英]Simple Injector: Injecting a property in a base class

幾個星期以來,我一直在使用Simple Injector依賴注入容器,並取得了巨大的成功。 我喜歡輕松配置它。 但是現在我有一個我不知道如何配置的設計。 我有一個基礎 class,其中有許多類型來自派生,我想將依賴項注入到基礎 class 的屬性中,但不必為每個派生的 class 配置它。 我試圖用屬性來做到這一點,但 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 中注入屬性?

提前感謝您的幫助。

關於屬性注入的 Simple Injector 文檔對此給出了非常清晰的解釋。 基本選項是:

  • 使用RegisterInitializer注冊初始化委托。
  • 覆蓋簡單注入器的PropertySelectionBehavior

正如文檔所解釋的,不建議使用RegisterInitializer對依賴項進行屬性注入; 僅在配置值上。

這使您可以覆蓋 Simple Injector 的PropertySelectionBehavior ,但是擁有一個基礎 class 本身就聞起來像是違反了 SOLID 規定。 請看下面的文章 它描述了為什么擁有一個基礎 class 可能是一個壞主意,並且文章為此提供了一個解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM