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

推荐订阅源

K
Kaspersky official blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cyberwarzone
Cyberwarzone
S
Securelist
S
Schneier on Security
V
Vulnerabilities – Threatpost
Latest news
Latest news
G
GRAHAM CLULEY
C
CERT Recently Published Vulnerability Notes
T
The Exploit Database - CXSecurity.com
Scott Helme
Scott Helme
Know Your Adversary
Know Your Adversary
雷峰网
雷峰网
S
SegmentFault 最新的问题
Jina AI
Jina AI
A
About on SuperTechFans
GbyAI
GbyAI
F
Full Disclosure
T
Tenable Blog
博客园 - 聂微东
P
Privacy International News Feed
Recorded Future
Recorded Future
PCI Perspectives
PCI Perspectives
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
NISL@THU
NISL@THU
Microsoft Security Blog
Microsoft Security Blog
C
Check Point Blog
The GitHub Blog
The GitHub Blog
IT之家
IT之家
S
Secure Thoughts
Cloudbric
Cloudbric
S
Security @ Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园_首页
N
News | PayPal Newsroom
有赞技术团队
有赞技术团队
I
Intezer
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
The Register - Security
The Register - Security
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
Martin Fowler
Martin Fowler
小众软件
小众软件
人人都是产品经理
人人都是产品经理
C
Cyber Attacks, Cyber Crime and Cyber Security
宝玉的分享
宝玉的分享
Schneier on Security
Schneier on Security

博客园 - 青玄鸟

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

运行效果如下