工厂方式注入

            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);
        }

参考文章:

ASP.NET CORE 内置的IOC解读及使用

相关文章:

  • 2022-12-23
  • 2023-02-26
  • 2021-08-09
  • 2022-12-23
  • 2022-12-23
  • 2021-10-23
  • 2022-12-23
  • 2022-03-05
猜你喜欢
  • 2021-08-15
  • 2021-07-12
  • 2022-12-23
  • 2021-12-07
  • 2022-01-20
  • 2021-12-03
相关资源
相似解决方案