如何实现.NET Core中同一接口不同实现的依赖注入?

摘要:工厂方式注入 然后在构造函数中通过如下方式获取具体实现 参考文章: "ASP.NET CORE 内置的IOC解读及使用"
工厂方式注入 services.AddSingleton(p => { ISingletonService func(int n) { return n switch { 1 => p.GetService<SingletonService1>(), 2 => p.GetService<SingletonService2>(), _ => throw new NotSupportedException(), }; } return (Func<int, ISingletonService>)func; }); 然后在构造函数中通过如下方式获取具体实现 private readonly SingletonService1 _singletonService1; private readonly SingletonService2 _singletonService2; public HealthController(Func<int, ISingletonService> func) { _singletonService1 = func(1); _singletonService2 = func(2); }