2014-02-24 325 views
1

是否有可能在具有2個構造函數的類中使用依賴注入?依賴注入與2構造函數

例如,假設我有一個界面:

public interface ILogger 
    { 
     void Log(LogLevel level, string message, string CallerID); 
    } 

和它的實現:

internal class NLogger : ILogger 
{ 
    private static NLog.Logger _logger; 

    public NLogger() 
    { 
     _logger = LogManager.GetCurrentClassLogger(); 
    } 

    public NLogger(ISomeService srv): this() 
    { 
     srv.doSomthing(); 
    } 

    public void Log(LogLevel level, string message, string CallerID) 
    { 
     //implementation 
    } 
} 

我要注入ISomeService以防萬一它存在於我的DI容器,並在情況下,它不存在 - 使用空構造函數並繼續工作,但不使用ISomeService

可能嗎?如果沒有,你有建議如何實現類似的東西?

+2

擁有多個構造函數[是反模式](http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=97)。請不要這樣做。 – Steven

回答

1

Unity默認情況下會選擇參數最多的構造函數。如果您希望在註冊映射時使用某個構造函數,則可以使用InjectionConstructor。

// Using default constructor 
this.unityContainer.RegisterType<ILogger, NLogger>(new InjectionConstructor()); 

// Using ISomeService constructor 
this.unityContainer.RegisterType<ILogger, NLogger>(new InjectionConstructor(new ResolvedParameter<ISomeService>())); 
1

一般來說,大多數IoC容器會選擇它可以滿足的最貪婪的構造函數。這意味着如果您有ISomeService註冊,它將選擇該構造函數,否則它將回退到默認的構造函數。

+0

我認爲這將是這種情況,但我試圖刪除ISomeService註冊,當我解決ILogger時,我得到一個異常 – Ofir

+2

@Ofir:這是因爲Unity是一個'組2'容器,正如[本文] (http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=97)。第2組是集裝箱中最無用的組。 – Steven

+0

謝謝,在我閱讀你的鏈接後,我看到'[OptionalDependency]'可以解決我的問題。我不知道這個功能。謝謝 – Ofir

相關問題