I have services that are derived from the same interface.
public interface IService { }
public class ServiceA : IService { }
public class ServiceB : IService
It is not supported by Microsoft.Extensions.DependencyInjection.
But you can plug-in another dependency injection mechanism, like StructureMap See it's Home page and it's GitHub Project.
It's not hard at all:
Add a dependency to StructureMap in your project.json:
"Structuremap.Microsoft.DependencyInjection" : "1.0.1",
Inject it into the ASP.NET pipeline inside ConfigureServices and register your classes (see docs)
public IServiceProvider ConfigureServices(IServiceCollection services) // returns IServiceProvider !
{
// Add framework services.
services.AddMvc();
services.AddWhatever();
//using StructureMap;
var container = new Container();
container.Configure(config =>
{
// Register stuff in container, using the StructureMap APIs...
config.For().Add(new Cat("CatA")).Named("A");
config.For().Add(new Cat("CatB")).Named("B");
config.For().Use("A"); // Optionally set a default
config.Populate(services);
});
return container.GetInstance();
}
Then, to get a named instance, you will need to request the IContainer
public class HomeController : Controller
{
public HomeController(IContainer injectedContainer)
{
var myPet = injectedContainer.GetInstance("B");
string name = myPet.Name; // Returns "CatB"
That's it.
For the example to build, you need
public interface IPet
{
string Name { get; set; }
}
public class Cat : IPet
{
public Cat(string name)
{
Name = name;
}
public string Name {get; set; }
}