Unity Factory Injection

爱⌒轻易说出口 提交于 2020-01-14 13:08:32

问题


I have an interface like the below one which I inject into unity container.

public interface IMyInstanceFactory
{
    IEnumerable<IMyInstance> GetAll();
}

All IMyInstance are known before runtime i.e they can be setup within the bootstrapper and can be retrieved from unity. My concrete implementation for IMyInstanceFactory is as below:

public class MyInstanceFactory:IMyInstanceFactory
{
    IUnityContainer _container;

    public MyInstanceFactory(IUnityContainer container)
    {
        _container = container;
    }
    public IEnumerable<IMyInstance> GetAll()
    {
        return _container.ResolveAll<IMyInstance>();
    }
}

..and in my bootstrapper I do something like this:

container.RegisterType<IMyInstance,MyInstance1>;
container.RegisterType<IMyInstance,MyInstance2>;
container.RegisterType<IMyInstance,MyInstance3>;
container.RegisterType<IMyInstanceFactory,MyInstanceFactory>;

This resolves everything beautifully. However, I do not want to take a dependency on the the container as such or implement IMyInstanceFactory just for this, is there a way I can set this up without implementing IMyInstanceFactory? Does Unity provide a facility for this?

Something of this sort..

container.RegisterType<IMyInstanceFactory,factory=>factory.GetAll()>().IsResolvedBy(unity.ResolveAll<IMyInstance>);

I know castle can do this, can Unity do something similar?


回答1:


There is a port of the Castle Windsor Typed Factory Facilities for Unity. It will generate an implementation of your interface and do the ResolveAll for you.

Your bootstrapping code should look something like this:

container.RegisterType<IMyInstance,MyInstance1>("1");
container.RegisterType<IMyInstance,MyInstance2>("2");
container.RegisterType<IMyInstance,MyInstance3>("3");
container.RegisterType<IMyInstanceFactory>(new TypedFactory());

The call to GetAll will be translated to the container call ResolveAll.

The port follows the same conventions described for Windsor.




回答2:


There is nothing wrong in passing a container to a factory, this works well if the factory is exposed as a singleton so that getting an instance does not require passing the container once again.

Another option would be to resolve the container with a service locator in a factory, since the locator is a singleton, this approach resembles the former.



来源:https://stackoverflow.com/questions/13749706/unity-factory-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!