.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应用程序中使用依赖注入的经验和建议. ...
随机推荐
- Android4.4开机动画播放视频
Android4.4系统启动时,播放自定义bootanimation.zip动画时,由于分辨率为1280x720,bootanimation.zip包也很大,播放太卡,所以将开机动画修改为播放视频.如 ...
- SpringBoot项目 maven打包时候提示程序包xxx不存在
A模块依赖B模块 A打包的时候会报程序包xxx不存在 这时候我们看下B模块的pom.xml文件是否加了 <build> <plugins> <plugin> < ...
- MySQL查找数据中相同的数据,并进行删除
查找表中多余的重复记录,重复记录是根据某个字段来判断 select * from 表名 where 字段 in (select 字段 from 表名 group by 字段 having count( ...
- UDP&串口调试助手用法(4)
接收配置用法 概览 保存文件 可将数据保存到文件和文件夹 如果选择的时文件,则需要自己手动选择保存的文件. 如果选择的时文件夹,则需要指定文件夹的类型和文件的后缀 支持保存文件类型: 文本文件和二进制 ...
- Linux蓝牙库blueZ
1.blueZ 官网 2.zigbee 网络库zigbee(可用在smart home devices)
- 【LeetCode】703. Kth Largest Element in a Stream 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 小根堆 日期 题目地址:https://leetco ...
- hud -5124-lines(线段树)
题目的意思是求重合层数最多的段(把点也看成段). 给的数据范围为N<1e5; ai<1e9; 有于N只有1e5;那么离散化一下可以将ai的范围映射到1e5,而不改变原端点的相对大小. 接下 ...
- 自我学习与理解:keras框架下的深度学习(三)回归问题
本文主要是使用keras对其有的波士顿房价数据集做一个回归预测,其代码架构与之前一样(都只是使用多层感知机):数据的预处理.搭建网络框架.编译.循环训练以及测试训练的网络模型.其中除了数据预处理与之前 ...
- Go语言核心36讲(新年彩蛋)--学习笔记
新年彩蛋 | 完整版思考题答案 基础概念篇 Go 语言在多个工作区中查找依赖包的时候是以怎样的顺序进行的? 答:你设置的环境变量GOPATH的值决定了这个顺序.如果你在GOPATH中设置了多个工作区, ...
- .Net Core&Agile Config配置中心
当服务逐渐的增多,对各服务的配置管理愈加重要,轻量级的配置中心,入手或是搭建都简单许多,基于.net core开发的轻量级配置中心AgileConfig,功能强大,上手简单. https://gith ...