Injecting multiple implementations with Dependency injection
I'm currently working on a ASP.NET Core Project and want to use the built-in Dependency Injection (DI) functionality.
Well, I started with an interface:
ICar
{
string Drive();
}
and want to implement the ICar interface multiple times like
public class BMW : ICar
{
public string Drive(){...};
}
public class Jaguar : ICar
{
public string Drive(){...};
}
and add the following in the Startup class
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddTransient<ICar, BMW>();
// or
services.AddTransient<ICar, Jaguar>();
}
Now I have to make a decision between two implementations and my decided class will set in every constructor that needs an ICar implementation. .
Otherwise DI don't make sense for me. How can i handle this issue properly?
https://media-www-asp.azureedge.net/media/44907/dependency-injection-golf.png?raw=true
In Unity it's possible to make something like this
container.RegisterType<IPerson, Male>("Male");
container.RegisterType<IPerson, Female>("Female");
and call the correct type like this
[Dependency("Male")]IPerson malePerson