如何使用Simple Injector组合多个工厂?

时间:2017-03-21 13:07:42

标签: c# factory-pattern simple-injector

SimpleInjectorBooFactory创建Boo消耗另一个工厂SimpleInjectorFooFactory来创建FooBoo类将具有相应的Foo类。

  • MyBoo将使用MyFoo
  • YourBoo将使用YourBoo

如何设置container来实现这一目标?我的一些想法是(1)将SimpleInjectorFooFactory注入SimpleInjectorBooFactory或(2)注入SimpleInjectorFooFactoryBoo或其类层次结构。

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();

0 个答案:

没有答案