How to inject IEnumerable using Microsoft Iity IOC container

I have a Service that requires input of several providers, see below, for example. How to use Unity to implement this feature?

public class MyService: IMyService { public MyService(IEnumerable<Provider> Providers); } 
+2
source share
2 answers

I know this is an old question, but maybe it will help someone else who stumbled upon this.

As long as you register implementations with a specific name, this can be easily entered. Then you will get all registered implementations.

 public class MyService: IMyService { public MyService(IProvider[] providers) { // Do something with the providers } } 

Just include them as an array. Unity will understand this. And when you register them, you can register them as such:

 container.RegisterType<IProvider, FooProvider>("Foo"); container.RegisterType<IProvider, BarProvider>("Bar"); 
0
source

One way is to enter UnityContainer itself, and then allow all the providers you need:

 public class MyService : IMyService { public class MyService(IUnityContainer iocContainer) { var providers = iocContainer.ResolveAll<IProvider>(); } } 

The only thing you need to do is register the UnityContainer somewhere in the setup:

 unityContainer.Register<IUnityContainer>(unityContainer, new ContainerControllerLifetimeManager()); 
-2
source

Source: https://habr.com/ru/post/1386506/


All Articles