我正在尝试找出注入(inject)带参数的自动工厂的正确方法,或者即使这可以通过 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 中使用最少的代码来做到这一点。
最佳答案
很抱歉成为那些回答自己问题的烦人的人之一,但我想通了。
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");
关于c# - 带有参数的Unity自动工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3825270/