工厂方式注入
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);
}
参考文章: