.net Core 同一接口不同实现的依赖注入

工厂方式注入

            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解读及使用

原文地址:https://www.cnblogs.com/rsls/p/12750680.html