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

前端 未结 24 1948
不思量自难忘°
不思量自难忘° 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 10:57

    Another option is to use the extension method GetServices from Microsoft.Extensions.DependencyInjection.

    Register your services as:

    services.AddSingleton();
    services.AddSingleton();
    services.AddSingleton();
    

    Then resolve with a little of Linq:

    var services = serviceProvider.GetServices();
    var serviceB = services.First(o => o.GetType() == typeof(ServiceB));
    

    or

    var serviceZ = services.First(o => o.Name.Equals("Z"));
    

    (assuming that IService has a string property called "Name")

    Make sure to have using Microsoft.Extensions.DependencyInjection;

    Update

    AspNet 2.1 source: GetServices

提交回复
热议问题