惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
Apple Machine Learning Research
Apple Machine Learning Research
WordPress大学
WordPress大学
博客园 - 司徒正美
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
爱范儿
爱范儿
月光博客
月光博客
The GitHub Blog
The GitHub Blog
M
MIT News - Artificial intelligence
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog
T
Tailwind CSS Blog
美团技术团队
D
Docker
V
Visual Studio Blog
Martin Fowler
Martin Fowler
博客园 - 聂微东
The Cloudflare Blog

博客园 - 青玄鸟

.NET 中优雅处理 Server-Sent Events 请求取消 vue3.0 + ts 实现上传工厂(oss与cos) Dapr 订阅者参数无法正确反序列化问题 .NET 代码整洁手册 Blazor项目通过docker和nginx部署为静态站点的步骤 Moq mock 方法返回null空指针异常 HttpClient with Stream HttpClient partial update HttpClient 基本使用 值对象的封装 只读集合类型属性实现 适配器模式 模板模式 最少知识原则 单例模式 抽象工厂 简单工厂、工厂方法、抽象工厂 工厂方法模式 使用 Visual Studio Code创建和执行T-SQL
基于接口隔离原则的依赖注入实现
青玄鸟 · 2020-07-21 · via 博客园 - 青玄鸟

接口隔离原则

不强迫接口的使用者依赖其不需要的接口

接口隔离原则的一般实现

    public interface IFoo
    {
        void DoSomeOperation();
    }

    public interface IBar
    {
        void DoAnotherOperation();
    }

    public class Qux : IFoo, IBar
    {
        public Qux()
        {
            Console.WriteLine("Qux instanced");
        }

        public void DoAnotherOperation()
        {
            Console.WriteLine("I am IBar");
        }

        public void DoSomeOperation()
        {
            Console.WriteLine("Just IFoo");
        }
    }

ASP.NET Core 依赖注入方式注入接口的实现类

为了使IFoo和IBar接口使用同一个Qux实例,可以使用以下方式注入所需服务

        static void Main(string[] args)
        {
            var root = new ServiceCollection()
                .AddScoped<Qux>()
                .AddScoped<IFoo>(provider=>provider.GetService<Qux>())
                .AddScoped<IBar>(provider => provider.GetService<Qux>())
                .BuildServiceProvider();

            using (var scope = root.CreateScope())
            {
                var provider = scope.ServiceProvider;
                provider.GetRequiredService<IFoo>();
                provider.GetRequiredService<IBar>();
            }

            Console.ReadLine();
        }

运行效果如下