3

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);
}
RoelF
  • 7,483
  • 5
  • 44
  • 67
Tony Woo
  • 198
  • 2
  • 7

2 Answers2

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");
smoksnes
  • 10,509
  • 4
  • 49
  • 74
-3

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());
RoelF
  • 7,483
  • 5
  • 44
  • 67
  • Thank you . I know this way, but I don't like it , since I need to write one more code:) – Tony Woo Mar 21 '13 at 00:39
  • 2
    Please don't share the container object with external classes. Only one class should know the ioc container! @TonyWoo: Use container.RegisterType, Provider[]>(); – bitsmuggler Aug 08 '13 at 12:07
  • in some situations you can't go around it. And I would suggest posting that comment as an answer. – RoelF Aug 08 '13 at 14:42