如何使用Unity通过工厂注入依赖项?

时间:2014-12-22 22:59:19

标签: c# .net dependency-injection unity-container

想象一下,我将通过工厂创建一些东西:

public sealed class MyClass
    : IMyClass
{
    private IMyDao MyDao { get; set; }

    public MyClass(IMyDaoFactory factory)
    {
        MyDao = factory.MyDao;
    }
}

这可以通过服务解决:

public sealed class MyService
    : IMyService
{
    private readonly IMyClass myClass;

    public MyService(IMyDaoFactory factory)
    {
        myClass = new MyClass(factory);
    }
}

在Unity中很容易接线:

var container = new UnityContainer();
container.RegisterType<IMyService, MyService>();
container.RegisterType<IMyDaoFactory, MyDaoFactory>();
container.RegisterType<IMyClass, MyClass>();

注意到MyClass的注册,如何设置Unity以便它自动注册并通过工厂解决?即然后我不再需要:

myClass = new MyClass(factory);

this.myClass = myClass; (passed through the constructor 
                         as IMyClass and resolved by Unity)

希望这是有道理的。提前谢谢。

1 个答案:

答案 0 :(得分:0)

尝试将MyService的构造函数切换为需要IMyClass的单个实例; Unity应该自动填补那里的空白,并根据类型签名进行实例化。

public MyService(IMyClass _myClass)
{
    myClass = _myClass;
}

虽然我也会改名,但是呃。