2010-09-29 39 views
13

我想找出正確的方法來注入一個自動工廠,它需要參數,或者即使這是可能的統一。統一自動工廠與參數

例如,我知道我能做到這一點:

public class TestLog 
{ 
    private Func<ILog> logFactory; 

    public TestLog(Func<ILog> logFactory) 
    { 
      this.logFactory = logFactory; 
    } 
    public ILog CreateLog() 
    { 
     return logFactory(); 
    } 
} 

Container.RegisterType<ILog, Log>(); 
TestLog test = Container.Resolve<TestLog>(); 
ILog log = test.CreateLog(); 

現在我就希望能夠做的是:

public class TestLog 
{ 
    private Func<string, ILog> logFactory; 

    public TestLog(Func<string, ILog> logFactory) 
    { 
      this.logFactory = logFactory; 
    } 
    public ILog CreateLog(string name) 
    { 
     return logFactory(name); 
    } 
} 

Container.RegisterType<ILog, Log>(); 
TestLog test = Container.Resolve<TestLog>(); 
ILog log = test.CreateLog("Test Name"); 

可惜,這是行不通的。我可以看到如何在Unity中創建自定義工廠以創建實例,似乎無法爲此示例提供任何清晰示例。

顯然我可以創建自己的工廠,但我正在尋找一種優雅的方式來在Unity中做到這一點,並用最少的代碼。

回答

28

對不起,成爲那些回答自己的問題,但我想出來的那些惱人的人之一。

public class TestLog 
{ 
    private Func<string, ILog> logFactory; 

    public TestLog(Func<string, ILog> logFactory) 
    { 
     this.logFactory = logFactory; 
    } 
    public ILog CreateLog(string name) 
    { 
     return logFactory(name); 
    } 
} 

Container.RegisterType<Func<string, ILog>>(
    new InjectionFactory(c => 
     new Func<string, ILog>(name => new Log(name)) 
    )); 

TestLog test = Container.Resolve<TestLog>(); 
ILog log = test.CreateLog("Test Name"); 
+0

是否有可能做這樣的事情,但使用構造函數注入? – dmigo 2015-06-18 14:08:13

+0

@Chesheersky上面的例子使用構造函數注入。 – TheCodeKing 2015-06-18 18:26:14

+0

對,我的錯誤:) – dmigo 2015-06-21 12:09:39

1

如果你正在尋找一個完全類型的工廠接口(允許XML文件和參數名稱,例如),你可以使用一個NuGet package我創建的,你可以利用簡單地通過定義一個接口工廠,然後將其與您要實例化的具體類型關聯。

代碼在GitHub上:https://github.com/PombeirP/FactoryGenerator

+0

正是我需要的。建議你添加一個例子到你的答案就像這裏:http://blog.ploeh.dk/2012/03/15/ImplementinganAbstractFactory/在動態代理部分。 – Ghosthack 2016-01-22 08:30:07

5

通過@TheCodeKing答案工作正常,但在大多數情況下,可以縮短爲以下(可能所有):

Container.RegisterInstance<Func<string, ILog>>(name => new Log(name)); 

(注意,我「M使用RegisterType()RegisterInstance()代替)

由於Func<>實施已經是一種工廠通常有否N將其包裹在InjectionFactory中。它只能確保Func<string, ILog>的每個分辨率都是一個新實例,我不能真正想到需要這樣的場景。