我试图找出正确的方法来注入带参数的自动工厂,或者说这是否在Unity中是可能的。
例如,我知道可以这样做:
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中实现此操作的方式。
RegisterType<Func<string, ILog>>(new InjectionFactory( ..)
?它并不明显... 我知道它确保了 test.CreateLog("dsffads") 能够被解决,但是 怎么做到的?,为什么要这么做? - Prokurors