Reputation: 370
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
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