我想找出正確的方法來注入一個自動工廠,它需要參數,或者即使這是可能的統一。統一自動工廠與參數
例如,我知道我能做到這一點:
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中做到這一點,並用最少的代碼。
是否有可能做這樣的事情,但使用構造函數注入? – dmigo 2015-06-18 14:08:13
@Chesheersky上面的例子使用構造函數注入。 – TheCodeKing 2015-06-18 18:26:14
對,我的錯誤:) – dmigo 2015-06-21 12:09:39