Unity Factory Injection

I have an interface like the one below that I insert into the units container.

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

All IMyInstance known before launch, that is, they can be configured in the boot block and can be extracted from one. My specific implementation for IMyInstanceFactory as follows:

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

It perfectly eliminates everything. However, I don’t want to depend on the container itself or implement IMyInstanceFactory just for that, is there a way I can install without implementing IMyInstanceFactory ? Does unity provide a means to this?

Something like that ..

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

I know a castle can do this, can Unity do something like this?

+4
source share
2 answers

There is a Windsor Typed Factory Castle Port Opportunity for Unity . It will create an implementation of your interface and make ResolveAll for you.

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

A GetAll call will translate into a ResolveAll container ResolveAll .

The port follows the same conventions as for Windsor.

+3
source

There is nothing wrong with transferring a container to a factory, this works well if the factory is displayed as a singleton, so there is no need to transfer the container again to get the instance.

Another option is to allow the container with the service locator in the factory, since the locator is singleton, this approach is similar to the first.

0
source

All Articles