2011-06-10 74 views
0

如果我有一個類,它在幾個構造函數參數,包括一個字符串,可以爲空,我目前使用以下語法對其進行註冊:Unity流利註冊 - 可以縮短嗎?

container.RegisterType<ISomething, Something>(
new InjectionConstructor(new InjectionParameter<string>(aString), typeof(ISomethingHelper), typeof(ISomethingManager))) 

我加InjectionParameter應付空的情況下, aString沒有這個,Unity抱怨。

這是所有必要或我可以精簡一下?

回答

0

空值是一個有點特殊的情況,因爲我們也無法從類型爲NULL的常數的類型(它只是涉及通過編譯類型的對象)。因此,寫一個小的幫助函數/類是沒有的,只是它儘可能短。

我可以看到寫這樣的事情:

public static class NullParam 
{ 
    public InjectionParameter OfType<T>() 
     where T : class 
    { 
     return new InjectionParameter<T>(null); 
    } 
} 

然後,你可以寫在上面:

container.RegisterType<ISomething, Something>(
    new InjectionConstructor(
     NullParam.OfType<string>, typeof(ISomethingHelper), typeof(ISomethingManager))); 

我不知道這是較短的,足以值得引進幫手。

的統一API的設計是圍繞規律性和可擴展性,而不是爲了簡潔和方便。這確實使一些事情變得更加理性。好的一點是,編寫小包裝和幫助程序很容易,使註冊代碼看起來像你想要的樣子。