我正在尝试找出正确的方法来注入一个带有参数的自动工厂,或者即使使用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中创建自定义工厂来创建实例,但似乎无法为这个例子提供任何清晰的例子。
显然,,我可以创建自己的工厂,但我正在寻找一种优雅的方式,用最少的代码在中做到这一点。
https://stackoverflow.com/questions/3825270
复制相似问题