调用工厂返回Unity IoC的类型

时间:2014-05-08 13:05:41

标签: c# dependency-injection inversion-of-control unity-container ioc-container

我有一家工厂:

public class FooFactory : IFooFactory
{
    public IFoo CreateFoo(IBar bar)
    {
        return new Foo(bar);
    }
}

我的Unity容器需要获得Foo的解析。

var container = new UnityContainer();

container.RegisterType<IBar, Bar>();
conatiner.RegisterType<IFooFactory,FooFactory>(
    new InjectionConstructor(new ResolvedParameter<IBar>())
container.RegisterType<IFoo, Foo>(????????);  //What should be here?

如何告诉Unity在工厂调用方法以获得IFoo

2 个答案:

答案 0 :(得分:1)

我认为你正试图过度设计这个 - 你有一个班级(FooFactory):

  • 当给出IBar个实例时,
  • 返回IFoo个实例

使用工厂生成IFoo个实例:

public class Greeter
{
  private readonly IFooFactory _fooFactory;

  public Greeter(IFooFactory fooFactory)
  {
    _fooFactory = fooFactory;
  }

  public string SayHelloWithABar(IBar bar)
  {
    IFoo foo = _fooFactory.CreateFoo(bar);

    // do something with your 'foo' instance ...

    return "hello!";
  }
}

答案 1 :(得分:0)

您可以使用InjectionFactory来完成。不过,我建议您切换为使用IFooFactory作为Bar中的依赖项。它使代码更容易理解。

更好:

public class Bar
{
    private IFoo _foo;

    public Bar(IFooFactory fooFactory)
    {
        _foo = fooFactory.Create(this);
    }
}