1、简介

  DI:Dependency Injection,即依赖注入,他是IOC的具体实现。

  在DI中,底层服务对象不再负责依赖关系的创建,而是交由顶端调用进行管理注入

  好处:降低组件之间的耦合度,使代码更加灵活

2、实例

  我们举个例子,有个User Login的功能,Login需要通过DB验证,DB需要读取Config和进行Log记录

  依赖关系如图

  

  DI的概念,就是把DB的依赖(Config&Log)提到User层,该怎么实现呢?

  接着往下走...

3、代码结构

  通过代码我们来看一下原理。

  框架说明:

    1)Service类库:Standard2.1,类库推荐都使用Standard,这样可以在Framework、core、net之间通用

    2)UserSite:Net5 控制台程序

  

  编码内容:

  ConfigService,包含两种实现方式

namespace ConfigService
{
public interface IConfig
{
public string GetValue(string key);//获取name的值
}
} using System;
namespace ConfigService
{
public class EnvironmentConfig : IConfig //从环境变量里面读取配置信息,自行添加到电脑User里面
{
public string GetValue(string key)
{
return Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User);
}
}
} using System.IO;
using System.Linq;
namespace ConfigService
{
public class IniFileConfig : IConfig //从ini文件读取配置信息,UserSite如果注入此服务,需要创建ini文件
{
string _filePath;
public IniFileConfig(string filePath)
{
this._filePath = filePath;
}
public string GetValue(string key)
{
string str = "";
var kv = File.ReadAllLines(_filePath)
.Select(x => x.Split("="))
.Select(x => new { key = x[0], value = x[1] })
.SingleOrDefault(x => x.key == key);
return kv?.value;
}
}
}

  LogService,简单实现

namespace LogService
{
public interface ILog
{
public void LogInfo(string msg);
public void LogError(string msg);
}
} using System;
namespace LogService
{
public class ConsoleLog : ILog
{
public void LogInfo(string msg)
{
Console.WriteLine($"Info:{msg}");
}
public void LogError(string msg)
{
Console.WriteLine($"Error:{msg}");
}
}
}

  DBService,只是做思路演示,这边只要读取到dblink就算访问数据库成功

namespace DBService
{
public interface IDBHelper
{
public bool CheckUser(string acc, string pwd);
}
} using LogService;
using ConfigService;
namespace DBService
{
public class SqlServerHelper : IDBHelper
{
private IConfig _config;
private ILog _log;
public SqlServerHelper(IConfig config,ILog log) //Net默认从构造函数进行以来注入
{
this._config = config;
this._log = log;
}
public bool CheckUser(string acc, string pwd)
{
var dblink = this._config.GetValue("dblink");
this._log.LogInfo($"获取数据库链接={dblink}");
if (string.IsNullOrWhiteSpace(dblink))
{
this._log.LogError($"登录失败");
return false;
}
this._log.LogInfo($"登录成功-{acc}-{pwd}");
return true;
}
}
}

  主题来了,UserSite Program代码如下:

  我们需要注入SqlServerHelper服务,就需要将其依赖项一同注入,这样就将具体实现类提到了顶端注入,从而进行解耦

  比如:读取配置文件,我希望从哪读取,就注入哪一个(注意,都注入的话,IConfig会以后注入的为准)

using System;
using ConfigService;
using LogService;
using DBService;
using Microsoft.Extensions.DependencyInjection; namespace UserSite
{
class Program
{
static void Main(string[] args)
{
ServiceCollection services = new ServiceCollection();
services.AddScoped<ILog, ConsoleLog>();
services.AddScoped<IConfig, EnvironmentConfig>(); //1、我希望从环境变量读取配置
services.AddScoped(typeof(IConfig), x => new IniFileConfig("db.ini")); //2、我希望从ini读取配置
services.AddScoped<IDBHelper, SqlServerHelper>();
using (var sp = services.BuildServiceProvider())
{
var service = sp.GetRequiredService<IDBHelper>();
service.CheckUser("kxy", "123");
};
Console.ReadLine();
}
}
}

  DI的简单原理就是这样。。

  

.Net DI(Dependency Injection)依赖注入机制的更多相关文章

  1. spring in action学习笔记一:DI(Dependency Injection)依赖注入之CI(Constructor Injection)构造器注入

    一:这里先说一下DI(Dependency Injection)依赖注入有种表现形式:一种是CI(Constructor Injection)构造方法注入,另一种是SI(Set Injection) ...

  2. Spring框架xml配置文件 复杂类型属性注入——数组 list map properties DI dependency injection 依赖注入——属性值的注入依赖于建立的对象(堆空间)

    Person类中的各种属性写法如下: package com.swift.person; import java.util.Arrays; import java.util.List; import ...

  3. Spring4 -03 -Dependency Injection (依赖注入) : 代码体现/配置xml/测试

    DI:中文名称:依赖注入 英文名称((Dependency Injection) DI 是什么? 3.1 DI 和IoC 是一样的,差不多一样的技术和模板! 3.2 当一个类(A)中需要依赖另一个类( ...

  4. asp.net core 系列之Dependency injection(依赖注入)

    这篇文章主要讲解asp.net core 依赖注入的一些内容. ASP.NET Core支持依赖注入.这是一种在类和其依赖之间实现控制反转的一种技术(IOC). 一.依赖注入概述 1.原始的代码 依赖 ...

  5. Benefits of Using the Spring Framework Dependency Injection 依赖注入 控制反转

    小结: 1. Dependency Injection is merely one concrete example of Inversion of Control. 依赖注入是仅仅是控制反转的一个具 ...

  6. 基于注解的DI(DI:Dependency Injection 依赖注入)

    注解方式xml里面就不需要注册bean了. 构建注解需要 1.导入spring-aop-4.2.1.RELEASE.jar 包  2.需要更换配置文件头,即添加相应的约束. 现在的Student类就要 ...

  7. 理解依赖注入(DI - Dependency Injection)

    系列教程 Spring 框架介绍 Spring 框架模块 Spring开发环境搭建(Eclipse) 创建一个简单的Spring应用 Spring 控制反转容器(Inversion of Contro ...

  8. ASP.NET Core Web 应用程序系列(一)- 使用ASP.NET Core内置的IoC容器DI进行批量依赖注入(MVC当中应用)

    在正式进入主题之前我们来看下几个概念: 一.依赖倒置 依赖倒置是编程五大原则之一,即: 1.上层模块不应该依赖于下层模块,它们共同依赖于一个抽象. 2.抽象不能依赖于具体,具体依赖于抽象. 其中上层就 ...

  9. 基于.NET平台的分层架构实战(六)——依赖注入机制及IoC的设计与实现[转]

    原文:http://www.cnblogs.com/leoo2sk/archive/2008/06/19/1225223.html 我们设计的分层架构,层与层之间应该是松散耦合的.因为是单向单一调用, ...

  10. ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)

    在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入. P ...

随机推荐

  1. 我做了第一个ChatGPT .net api聊天库

    最近这个ChatGPT很火啊,看了B站上很多视频,自己非常手痒,高低自己得整一个啊,但是让我很难受的是,翻遍了github前十页,竟然没有一个C#的ChatGPT项目,我好难受啊!那能怎么办?自己搞一 ...

  2. RuntimeError: setuptools >= 41 required to build

    使用命令python setup.py install 安装第三方库报RuntimeError: setuptools >= 41 required to build 原因setuptools版 ...

  3. nuxt.js安装使用

    首先要学会看文档,https://www.nuxtjs.cn/guide/configuration 一.创建项目,并运行 终端运行 npx create-nuxt-app <项目名> ( ...

  4. k3s安装kubernetes环境

    官方文档:https://docs.rancher.cn/k3s/ 官方文档:https://rancher.com/docs/k3s/latest/en/installation/install-o ...

  5. shape {select ...} append ({select ...} RELATE ID TO PARAMETER 0,ID TO PARAMETER 1)

    1.问题描述 最近在写vb.net的时候,碰到了一个有点棘手的问题.就是在vb里面去解决一对多的关系. 对应关系如下,一个合同会对应多个开票. 最简单暴力的方法就是循环查询了,但是这样子肯定不行的.如 ...

  6. ubunut安装qtcreater

    安装gcc 1 kxb@kxb:~$ gcc -v 2 3 Command 'gcc' not found, but can be installed with: 4 5 sudo apt insta ...

  7. ArcEngine开发 - 打开地图读取图层

    地图文档(IMapDocument)对象是ArcEngine开发最基本对象,可以说是所有操作的第一步.使用IMapDocument可以检查和打开地图文档,读取图层信息和文档信息,为源GIS并为您详细分 ...

  8. C Primer Plus 5.11 編程練習

    /*C Primer Plus (5.10) 9*/ 1 #include<stdio.h> 2 #define G 103 3 int main() 4 { 5 char ch=96; ...

  9. sstream中的stringstream怎么用

    sstream中的stringstream怎么用 1.cin cin是从缓冲区读入,会把空格.回车等不可见的字符当做是分割,跳过.并且最后读入之后,后面会有剩余的部分,比如空格.回车等. 2.getl ...

  10. VSCode 创建flutter项目和运行、调试、热更新项目

    1.创建--在終端輸入命令 flutter create 项目名 2.普通运行--在终端输入命令 flutter run 3.打开你的虚拟机或者是连上手机等待页面加载 4.普通運行情況下修改代碼后想要 ...