How to register multiple implementations of the same interface in Asp.Net Core?

前端 未结 24 1975
不思量自难忘°
不思量自难忘° 2020-11-22 10:16

I have services that are derived from the same interface.

public interface IService { }
public class ServiceA : IService { }
public class ServiceB : IService         


        
24条回答
  •  无人及你
    2020-11-22 11:01

    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:

    1. Add a dependency to StructureMap in your project.json:

      "Structuremap.Microsoft.DependencyInjection" : "1.0.1",
      
    2. 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();
      }
      
    3. 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; }
        }
    

提交回复
热议问题