2011-06-03 45 views
4

幾個星期以來,我一直在使用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的財產?

在此先感謝您的幫助。

回答

9

簡單注射器documentation on property injection給出了一個非常清楚的解釋。基本選項有:

  • 使用RegisterInitializer註冊初始化代理。
  • 覆蓋簡單注射器的PropertySelectionBehavior

正如文檔解釋,不建議使用RegisterInitializer屬性注入依賴;只在配置值上。

這會讓您忽略簡單注射器的PropertySelectionBehavior,但它本身具有基本類似於SOLID違規的氣味。請看看the following article。它描述了爲什麼有一個基類可能是一個壞主意,文章提出了一個解決方案。

+0

這很好。謝謝。 – Smitha 2011-06-03 13:58:27

相關問題