108
108

Reputation: 370

How do I inject multiple instances of a generic interface?

I have an interface like this:

public interface IService<T>  
{  
    void DoSomething(T obj)  
}  

And several implementations:

public class ServiceA : IService<A>
{  
    public void DoSomething(A a)  
} 
public class ServiceB : IService<B>  
{  
    public void DoSomething(B b)  
}

How can I inject all the instances that implement IService<T> in the constructor of a consuming class?

Upvotes: 1

Views: 1164

Answers (1)

Martin Ullrich
Martin Ullrich

Reputation: 100581

You will need to inject IServiceProvider into your consumer and then use a resolving method like serviceProvider.GetRequiredService<IService<T>>() to resolve the registered generic service.

It violates some form of DI principles but is the way to get the correct implementation inside the method. Otherwise you would have to create a whole class (Consumer<T>) that is registered with a factory that does a similar call to set up Consumer<T>.

Upvotes: 2

Related Questions