How to inject IEnumerable using Microsoft Unity IOC container

纵饮孤独 提交于 2019-12-12 13:28:29

问题


I have a Service that need inject more than one provider, see below for example. How to use Unity to implement this feature?

public class MyService: IMyService
{
    public MyService(IEnumerable<Provider> Providers);
}

回答1:


I know this is an old question, but maybe this will help someone else that stumbles upon this.

As long as you register the implementations with a specific name, this is possible to easily inject. You will then get all registered implementations.

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

Just make sure to inject 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");



回答2:


One way is to inject the UnityContainer itself, and then resolve all the Providers you need:

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

The only thing you will need to do is register the UnityContainer with itself somewhere on setup:

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


来源:https://stackoverflow.com/questions/15518283/how-to-inject-ienumerable-using-microsoft-unity-ioc-container

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