我SimpleInjectorBooFactory
创建Boo
消耗另一个工厂SimpleInjectorFooFactory
来创建Foo
。 Boo
类将具有相应的Foo
类。
如何设置container
来实现这一目标?我的一些想法是(1)将SimpleInjectorFooFactory
注入SimpleInjectorBooFactory
或(2)注入SimpleInjectorFooFactory
至Boo
或其类层次结构。
private sealed class SimpleInjectorBarFactory : IBarFactory {
private readonly Container container;
public SimpleInjectorBarFactory(Container container) {
this.container = container;
}
public Bar CreateBar() {
return this.container.GetInstance<Bar>();
}
}
container.RegisterSingleton<IBarFactory, SimpleInjectorBarFactory>();
public class Bar
{
public Bar()
{
}
// TODO: Create MyFoo and call method on it.
public CallFoo()
{
SimpleInjectorFooFactory.CreateMyFoo().IsCalled();
}
}
private sealed class SimpleInjectorFooFactory : IFooFactory {
public MyFoo CreateMyFoo() {
return this.container.GetInstance<MyFoo>();
}
public YourFoo CreateYourFoo() {
return this.container.GetInstance<YourFoo>();
}
}
更新:
以下是我尝试用多个工厂解决的原始问题。
var container = new Container();
public Setup()
{
var bars = new Dictionary<string, InstanceProducer<IBar>>
{
{ "MyBar", Lifestyle.Transient.CreateProducer<IBar, MyBar>(container) },
{ "YourBar", Lifestyle.Transient.CreateProducer<IBar, YourBar>(container) },
};
container.RegisterSingleton<IBarFactory>(
new BarFactory(container, bars));
}
private sealed class BarFactory : IBarFactory {
private readonly Container container;
private readonly Dictionary<string, InstanceProducer<IBar>> bars;
public BarFactory(Container container, bars) {
this.container = container;
this.bars = bars;
}
public MyBar CreateBar(String barName)
{
return this.bars[barName].GetInstance();
}
}
public class MyBar : IBar
{
MyFoo myfoo;
public MyBar(MyFoo myFoo)
{
this.myfoo = myFoo;
}
public Process()
{
// TODO: display yourfoo.FileContents
}
}
public class YourBar : IBar
{
YourFoo yourfoo;
public YourBar(YourFoo yourFoo)
{
this.yourfoo = yourFoo;
}
public Process()
{
// TODO: display yourfoo.FileContents
}
}
public class Foo
{
protected string FileContents;
public void FetchFileContents(string fileName)
{
// Read into FileContents
}
}
// Using
var barFactory = container.GetInstance<IBarFactory>();
var myBar = barFactory.CreateBar("MayBar");
// Foo.FetchFileContents has to be called before myBar.Process is called.
myBar.Process();