.Net Core依赖注入
一、配置文件的读取
利用Startup类中的configuration读取appsettings.json中的配置
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"option1": "value1_from_json",
"option2": 2,
"subsection": {
"suboption1": "subvalue1_from_json",
"Read": [
"Data Source=.; Database=Customers_New1; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True",
"Data Source=ElevenPC; Database=Customers_New2; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True",
"Data Source=.; Database=Customers_New3; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True"
]
},
"wizards": [
{
"Name": "Gandalf",
"Age": "1000"
},
{
"Name": "Harry",
"Age": "17"
}
],
"AllowedHosts": "*"
}
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
this.Configuration["Option1"]
this.Configuration["subsection:suboption1"]
string[] _SqlConnectionStringRead = this._iConfiguration.GetSection("subsection").GetSection("Read").GetChildren().Select(s => s.Value).ToArray();
二、自带IOC容器
1.基本使用
- NuGet安装引用Microsoft.Extensions.DependencyInjection;
- 实例化容器
- 注册服务
- 创建一个System.IServiceProvider提供程序
- 创建实例
using Microsoft.Extensions.DependencyInjection;
IServiceCollection container = new ServiceCollection();
container.AddTransient<Interface,class>();
IServiceProvider provider = container.BuildServiceProvider();
_Interface interface = provider.GetService<_Interface>()
2.服务类型
1.container.AddTransient为瞬时生命周期,每次创建都是一个全新的实例
IServiceCollection container = new ServiceCollection();
container.AddTransient<Interface,class>();
IServiceProvider provider = container.BuildServiceProvider();
_Interface interface = provider.GetService<_Interface>();
_Interface interface2 = provider.GetService<_Interface>();
bool bResult = object.ReferenceEquals(interface, interface2);
//b is false
2.container.AddSingleton单例:全容器都是一个
IServiceCollection container = new ServiceCollection();
container.AddSingleton<Interface,class>();
IServiceProvider provider = container.BuildServiceProvider();
_Interface interface = provider.GetService<_Interface>();
_Interface interface2 = provider.GetService<_Interface>();
bool bResult = object.ReferenceEquals(interface, interface2);
//b is True
3.container.AddScoped请求单例,一个请求代表一个作用域
IServiceCollection container = new ServiceCollection();
container.AddScoped<Interface,class>();
IServiceProvider provider = container.BuildServiceProvider();
//创建一个Scope作用域,那么由这个域创建的实例是独立的(相较Scope1)
IServiceScope Scope = provider.CreateScope();
//创建一个Scope1作用域,那么由这个域创建的实例是独立的
IServiceScope Scope1 = provider.CreateScope();
_Interface interface =Scope.ServiceProvider.GetService<_Interface>();
_Interface interface2 = Scope1.ServiceProvider.GetService<_Interface>();
bool bResult = object.ReferenceEquals(interface, interface2);
//b is false
三、自带IOC容器(IServiceCollection)基础
1.生命周期
1.瞬时,即时构造,即时销毁
services.AddTransient<ITestServiceA, TestServiceA>();
2.单例,永远只构造一次
services.AddSingleton<ITestServiceB, TestServiceB>();
3.作用域单例,一次请求只构造一个
services.AddScoped<ITestServiceC, TestServiceC>();
2.实例解析
public TestServiceA()
{
Console.WriteLine($"{this.GetType().Name}被构造。。。");
}
public TestServiceB(ITestServiceA iTestServiceA)
{
Console.WriteLine($"{this.GetType().Name}被构造。。。");
}
public TestServiceC(ITestServiceB iTestServiceB)
{
Console.WriteLine($"{this.GetType().Name}被构造。。。");
}
public TestServiceD()
{
Console.WriteLine($"{this.GetType().Name}被构造。。。");
}
public TestServiceE(ITestServiceC serviceC)
{
Console.WriteLine($"{this.GetType().Name}被构造。。。");
}
//1.A类构造
//2.B类构造需要A类
//3.C类构造需要B类
//4.D类构造
//5.E类构造需要C类
//瞬时
services.AddTransient<ITestServiceA, TestServiceA>();
//单例
services.AddSingleton<ITestServiceB, TestServiceB>();
//作用域单例
services.AddScoped<ITestServiceC, TestServiceC>();
//瞬时
services.AddTransient<ITestServiceD, TestServiceD>();
//瞬时
services.AddTransient<ITestServiceE, TestServiceE>();
第一次请求解析
1.开始构造A类,因为是瞬时生命周期那么第一次请求就会被构造,然后销毁
2.在构造B类时需要A类,那么会首先构造A类(因为A类瞬时上一次已经被销毁),然后构造B类为单例
3.开始构造C,在构造时需要B类,因为B类全局单例,那就会直接构造C为作用域单例
4.直接构造瞬时D类
5.开始构造E类,构造式需要C类,因为C类为作用域单例,那么就会直接构造E类为瞬时
第一次请求结论
- 输出A
- 输出A,B
- 输出C
- 输出D
- 输出E
第二次请求解析
1.开始构造A类,因为是瞬时生命周期那么第二次请求就会重新被构造,然后销毁
2.在构造B类时因为在第一次请求时已经构造为单例,所以不再被构造
3.开始重新构造C,因为C在第二次请求为新的作用域,在构造时需要B类,因为B类全局单例,那就会直接构造C为作用域单例
4.直接构造瞬时D类
5.开始构造E类,构造式需要C类,因为C类为作用域单例,那么就会直接构造E类为瞬时
第二次请求结论
1.输出A
2.输出C
3.输出D
4.输出E
如果不想通过构造全部自动注入,能自定义注入
1.using Microsoft.Extensions.DependencyInjection;
2.首先注入 IServiceProvider serviceProvider,利用serviceProcider.GetService();生成需要的实例
四、利用AutoFac容器替换自带容器
1.下载Autofac.Extensions.DependencyInjection和Autofac包
2.在Program网站启动时替换默认IOC工厂实例为Autofac,UseServiceProviderFactory(new AutofacServiceProviderFactory())
3.在Startup类中添加方法public void ConfigureContainer(ContainerBuilder services){services.RegisterType().As().SingleInstance();}
//返回值为IServiceProvider
public IServiceProvider ConfigureContainer(ContainerBuilder services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//services.RegisterType<TestServiceE>().As<ITestServiceE>().SingleInstance();
services.RegisterModule<CustomMoudle>();
}
1.批量注册模块
public class CustomAutofacModule : Module
{
//重新load 添加注册服务
//可以实现实例控制
//接口约束
protected override void Load(ContainerBuilder containerBuilder)
{
containerBuilder.Register(c => new CustomAutofacAop());
//设置为属性注入
containerBuilder.RegisterType<TestServiceA>().As<ITestServiceA>().SingleInstance().PropertiesAutowired();
containerBuilder.RegisterType<TestServiceC>().As<ITestServiceC>();
containerBuilder.RegisterType<TestServiceB>().As<ITestServiceB>();
containerBuilder.RegisterType<TestServiceD>().As<ITestServiceD>();
containerBuilder.RegisterType<A>().As<IA>().EnableInterfaceInterceptors();
}
}
五、利用AutoFac实现AOP
1.基本使用
1.NuGet安装引用Autofac.Extras.DynamicProxy
2.引用using Autofac.Extras.DynamicProxy;
3.创建类库继承自IInterceptor实现接口
4.自定义的Autofac的AOP扩展
//注册,模块
public class CustomAutofacModule : Module
{
//重新load 添加注册服务
//可以实现实例控制
//接口约束
protected override void Load(ContainerBuilder containerBuilder)
{
//注册AOP
containerBuilder.Register(c => new CustomAutofacAop());
//开启aop扩展
containerBuilder.RegisterType<A>().As<IA>().EnableInterfaceInterceptors();
}
}
public class CustomAutofacAop : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine($"invocation.Methond={invocation.Method}");
Console.WriteLine($"invocation.Arguments={string.Join(",", invocation.Arguments)}");
invocation.Proceed(); //继续执行
Console.WriteLine($"方法{invocation.Method}执行完成了");
}
}
.Net Core依赖注入的更多相关文章
- # ASP.NET Core依赖注入解读&使用Autofac替代实现
标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Aut ...
- net core 依赖注入问题
net core 依赖注入问题 最近.net core可以跨平台了,这是一个伟大的事情,为了可以赶上两年以后的跨平台部署大潮,我也加入到了学习之列.今天研究的是依赖注入,但是我发现一个问题,困扰我很久 ...
- NET Core依赖注入解读&使用Autofac替代实现
NET Core依赖注入解读&使用Autofac替代实现 标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. ...
- 实现BUG自动检测 - ASP.NET Core依赖注入
我个人比较懒,能自动做的事绝不手动做,最近在用ASP.NET Core写一个项目,过程中会积累一些方便的工具类或框架,分享出来欢迎大家点评. 如果以后有时间的话,我打算写一个系列的[实现BUG自动检测 ...
- [译]ASP.NET Core依赖注入深入讨论
原文链接:ASP.NET Core Dependency Injection Deep Dive - Joonas W's blog 这篇文章我们来深入探讨ASP.NET Core.MVC Core中 ...
- asp.net core 依赖注入几种常见情况
先读一篇注入入门 全面理解 ASP.NET Core 依赖注入, 学习一下基本使用 然后学习一招, 不使用接口规范, 直接写功能类, 一般情况下可以用来做单例. 参考https://www.cnblo ...
- ASP.NET Core依赖注入——依赖注入最佳实践
在这篇文章中,我们将深入研究.NET Core和ASP.NET Core MVC中的依赖注入,将介绍几乎所有可能的选项,依赖注入是ASP.Net Core的核心,我将分享在ASP.Net Core应用 ...
- 自动化CodeReview - ASP.NET Core依赖注入
自动化CodeReview系列目录 自动化CodeReview - ASP.NET Core依赖注入 自动化CodeReview - ASP.NET Core请求参数验证 我个人比较懒,能自动做的事绝 ...
- ASP.NET Core 依赖注入最佳实践——提示与技巧
在这篇文章,我将分享一些在ASP.NET Core程序中使用依赖注入的个人经验和建议.这些原则背后的动机如下: 高效地设计服务和它们的依赖. 预防多线程问题. 预防内存泄漏. 预防潜在的BUG. 这篇 ...
- ASP.NET Core依赖注入最佳实践,提示&技巧
分享翻译一篇Abp框架作者(Halil İbrahim Kalkan)关于ASP.NET Core依赖注入的博文. 在本文中,我将分享我在ASP.NET Core应用程序中使用依赖注入的经验和建议. ...
随机推荐
- JAVA中json对象转JAVA对象,JSON数组(JSONArray)转集合(List)
json格式 {userId:'1',message:'2',create_time:'2020-03-28 20:58:11',create_date:'2020-03-28'}JAVA对象 Cha ...
- 【LeetCode】156. Binary Tree Upside Down 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leet ...
- 【LeetCode】910. Smallest Range II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- Leapin' Lizards(hdu 2732)
Leapin' Lizards Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)T ...
- Explain执行计划详解
一.id id: :表示查询中执行select子句或者操作表的顺序,id的值越大,代表优先级越高,越先执行. id大致会出现 3种情况 二.select_type select_type:表示 sel ...
- TensorFlow.NET机器学习入门【8】采用GPU进行学习
随着网络越来约复杂,训练难度越来越大,有条件的可以采用GPU进行学习.本文介绍如何在GPU环境下使用TensorFlow.NET. TensorFlow.NET使用GPU非常的简单,代码不用做任何修改 ...
- Capstone CS5265规格书|CS5265参数|TYPEC转HDMI音视频转换拓展坞芯片
一.CS5265总概 Capstone CS5265 USB Type-C到HDMI转换器结合了USB Type-C输入接口和数字高清多媒体接口(HDMI)输出.嵌入式微控制器(MCU)基于工业标准8 ...
- 元宇宙(metaverse)中文社区-工程实践
欢迎访问元宇宙中文社区,在这里大家可以提问,回答,分享,诉说,一起构建一个元宇宙社区. 2021年"元宇宙"的这个词的火热程度在业内绝对不亚于疫情,趁着这个热度,本文记录了如何搭建 ...
- 编写Java程序,定义一个类似于ArrayList集合类
返回本章节 返回作业目录 需求说明: 设计一个类似于ArrayList的集合类ListArray. ListArray类模拟实现动态数组,在该类定义一个方法用于实现元素的添加功能,以及用于获取List ...
- Dapper的封装、二次封装、官方扩展包封装,以及ADO.NET原生封装
前几天偶然看到了dapper,由于以前没有用过,只用过ef core,稍微看了一下,然后写了一些简单的可复用的封装. Dapper的用法比较接近ADO.NET所以性能也是比较快.所以我们先来看看使用A ...