2013-03-29 32 views
2

假設我有以下類。使用Unity解析各種類型的特定構造函數參數

public class Service1 
{ 
    public Service1(Dependency1 dependency1, Dependency2 dependency2, string myAppSetting) 
    { 
    } 
} 

public class Service2 
{ 
    public Service2(DependencyA dependency1, ..., DependencyD dependency4, string myAppSetting) 
    { 
    } 
} 

Unity容器用於通過依賴注入填充構造函數參數; container.Resolve(..)方法永遠不會直接調用。

上述類有各種參數,但最後一個參數string myAppSetting總是相同的。有沒有辦法將Unity容器配置爲始終使用特定的基元類型和名稱將參數解析爲不同類中的特定值?

我知道你可以爲每個類型註冊注入構造函數,這對我來說似乎很脆弱。另一種方式可能是將字符串參數包裝在自定義類中。但我想知道是否有辦法處理特定的原始類型構造函數參數。

回答

2

我製作了一個界面來包裝我的AppSettings。這允許我將應用程序設置注入到我的類型中。

IAppSettings

public interface IAppSettings { 
    string MySetting { get; set; } 
    ... 
} 

UnityConfig

container.RegisterInstance<IAppSettings>(AppSettings.Current); 
container.RegisterType<IService1, Service1>(); 
container.RegisterType<IService2, Service2>(); 

服務1

public class Service1 
{ 
    public Service1(Dependency1 dependency1, Dependency2 dependency2, IAppSettings appSettings) 
    { 
     var mySetting = appSettings.MySetting; 
    } 
} 

這裏有一些OPTI附件爲您的基本參數:Register a type with primitive-arguments constructor?

+1

聽起來像最好的解決方法是將所有原始參數包裝在類/接口中。 –

+0

您需要最終解決這些原語。所以你會需要某種類型的參數列表的生成器類來保持你的Unity配置不變 - 你尋求的。 – Jasen

0

我不認爲你可以得到統一的解決所有string參數命名爲「myAppSettings」任何類。但是,您可以通過名稱爲特定的類解析參數。類似於:

Container.RegisterType<Service2, Service2>(
      new InjectionConstructor(
        new ResolvedParameter<string>(), 
         "myAppSetting")); 
+0

那豈不是更喜歡 「新InjectionConstructor(新ResolvedParameter (),ResolvedParameter (),ResolvedParameter (),ResolvedParameter (), 」myAppSettingValue「));」?我的問題是,如果您添加或刪除注入的依賴項,那麼代碼將會中斷。 –

相關問題