美文网首页
.net Core 同一接口不同实现的依赖注入

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

作者: 0非空0 | 来源:发表于2020-04-22 11:06 被阅读0次

    工厂方式注入

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

    相关文章

      网友评论

          本文标题:.net Core 同一接口不同实现的依赖注入

          本文链接:https://www.haomeiwen.com/subject/rtibihtx.html