ASP.NET Core 下的依赖注入(一)
本文介绍利用 Microsoft.Extensions.Configuration.Binder.dll 来实现超级简单的注入。
1. appsettings.json 中定义配置
假设我们有如下配置:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Tecent": {
"Qzone": {
"Url": "http://i.qq.com",
"CName": "QQ空间",
"Age":
},
"Weixin": {
}
}
}
2. 定义配置模型类
public interface ITecentConfig
{
QzoneConfig Qzone { get; set; }
}
public class TecentConfig : ITecentConfig
{
public QzoneConfig Qzone { get; set; }
}
public class QzoneConfig
{
public string Url { get; set; } public string CName { get; set; } public int Age { get; set; }
}
3. Nuget 中引用 Microsoft.Extensions.Configuration.Binder.dll
4. 编写 ServiceCollection 的扩展方法
public static class ServiceCollectionExtensions
{
public static void ConfigureApplicationServices(this IServiceCollection services, IConfiguration configuration)
{
ITecentConfig tencentConfig = services.ConfigureStartupConfig<ITecentConfig, TecentConfig>(configuration.GetSection("Tecent")); //由于已经通过依赖注入了,并且单例模式,下面通过依赖注入读取配置。 } public static TConfig ConfigureStartupConfig<TConfig>(this IServiceCollection services, IConfiguration configuration)
where TConfig : class, new()
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
var config = new TConfig();
configuration.Bind(config);
services.AddSingleton(config);
//.NET Core DI 为我们提供的实例生命周其包括三种:
//Transient: 每一次GetService都会创建一个新的实例
//Scoped: 在同一个Scope内只初始化一个实例 ,可以
// 理解为( 每一个request级别只创建一个实例,同一个http request会在一个 scope内)
//Singleton :整个应用程序生命周期以内只创建一个实例
return config;
} public static IConfig ConfigureStartupConfig<IConfig, ConfigImpl>(this IServiceCollection services, IConfiguration configuration)
where ConfigImpl : class, IConfig, new()
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
var config = new ConfigImpl();
configuration.Bind(config);
services.AddSingleton(typeof(IConfig), config);
return config;
}
}
这里需要解释一下,这里有 2 个重载方法 ConfigureStartupConfig, 第一个表示不用接口(或者抽象父类),直接读取配置成我们自己的配置模型,然后依赖注入单例。第二个方法表示只依赖接口或者抽象父类(指:我们自己定义的 ITencentConfig),不依赖具体的子类(指:我们自己定义的 TecentConfig)。
5. 在 Startup.cs 中注册服务
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
});
services.ConfigureApplicationServices(Configuration);//注册我们自定义的服务 //注册自定义的模型绑定
services.AddMvc()
.AddNewtonsoftJson();
services.AddRazorPages();
}
}
6. MVC 控制器中构造函数注入
public class HomeController : Controller
{
private ITecentConfig _tecentConfig; public HomeController(ITecentConfig tecentConfig)
{
_tecentConfig = tecentConfig;
} public IActionResult About()
{
return Content(string.Format("这个是 About 介绍。{0}: {1}。HashCode:{2}",
_tecentConfig.Qzone.CName,
_tecentConfig.Qzone.Url,
_tecentConfig.GetHashCode()
)
);
}
}
7. 效果图


谢谢浏览!
ASP.NET Core 下的依赖注入(一)的更多相关文章
- ASP.NET Core中的依赖注入(1):控制反转(IoC)
ASP.NET Core在启动以及后续针对每个请求的处理过程中的各个环节都需要相应的组件提供相应的服务,为了方便对这些组件进行定制,ASP.NET通过定义接口的方式对它们进行了"标准化&qu ...
- ASP.NET Core中的依赖注入(3): 服务的注册与提供
在采用了依赖注入的应用中,我们总是直接利用DI容器直接获取所需的服务实例,换句话说,DI容器起到了一个服务提供者的角色,它能够根据我们提供的服务描述信息提供一个可用的服务对象.ASP.NET Core ...
- ASP.NET Core中的依赖注入(4): 构造函数的选择与服务生命周期管理
ServiceProvider最终提供的服务实例都是根据对应的ServiceDescriptor创建的,对于一个具体的ServiceDescriptor对象来说,如果它的ImplementationI ...
- ASP.NET Core 中的依赖注入
目录 什么是依赖注入 ASP .NET Core 中使用依赖注入 注册 使用 释放 替换为其它的 Ioc 容器 参考 什么是依赖注入 软件设计原则中有一个依赖倒置原则(DIP),为了更好的解耦,讲究要 ...
- ASP.NET Core中的依赖注入(2):依赖注入(DI)
IoC主要体现了这样一种设计思想:通过将一组通用流程的控制从应用转移到框架之中以实现对流程的复用,同时采用"好莱坞原则"是应用程序以被动的方式实现对流程的定制.我们可以采用若干设计 ...
- ASP.NET Core中的依赖注入(5): ServiceProvider实现揭秘 【总体设计 】
本系列前面的文章我们主要以编程的角度对ASP.NET Core的依赖注入系统进行了详细的介绍,如果读者朋友们对这些内容具有深刻的理解,我相信你们已经可以正确是使用这些与依赖注入相关的API了.如果你还 ...
- ASP.NET Core中的依赖注入(5): ServiceProvider实现揭秘 【解读ServiceCallSite 】
通过上一篇的介绍我们应该对实现在ServiceProvider的总体设计有了一个大致的了解,但是我们刻意回避一个重要的话题,即服务实例最终究竟是采用何种方式提供出来的.ServiceProvider最 ...
- ASP.NET Core中的依赖注入(5):ServicePrvider实现揭秘【补充漏掉的细节】
到目前为止,我们定义的ServiceProvider已经实现了基本的服务提供和回收功能,但是依然漏掉了一些必需的细节特性.这些特性包括如何针对IServiceProvider接口提供一个Service ...
- ASP.NET Core 中的 依赖注入介绍
ASP.NET Core 依赖注入 HomeController public class HomeController : Controller { private IStudentReposito ...
随机推荐
- Vault安装、配置、使用
一.环境搭建 官网指导步骤:https://learn.hashicorp.com/vault/#getting-started 1. 下载vault安装文件 2. dev环境启动 ./vault s ...
- shell 编程记录
1 文件比较运算符-e filename 如果 filename存在,则为真 [ -e /var/log/syslog ]-d filename 如果 filename为目录,则为真 [ -d /tm ...
- 12.22 大湾区.NET Meet 大会
今年的 Connect(); 主题更加聚焦开发者工具生产力.开源,以及无服务器(Serverless)云服务. Visual Studio 2019 AI 智能加持的 IntelliCode.实时代码 ...
- javaScript设计模式之面向对象编程(object-oriented programming,OOP)(二)
接上一篇 面向对象编程的理解? 答:面向对象编程,就是将你的需求抽象成一个对象,然后针对这个对象分析其特征(属性)与动作(方法).这个对象我们称之为类.面向对象编程思想其中一个特点就是封装,就是把你需 ...
- MAC系统上安装Apache ab测试工具
第一步:下载 Apache HTTP Server http://httpd.apache.org/download.cgi#apache24 第二步:安装brew工具 https://brew.sh ...
- 【Android Studio安装部署系列】十六、Android studio在layout目录下新建子目录
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 概述 一般用于分类显示不同模块的layout布局文件. 在res/layout文件夹下创建子目录 res/layout鼠标右键——New— ...
- Litepal【开源数据库ORM框架】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 好用的数据库框架. 效果图 代码分析 本篇主要是整理Litepal的引入和增删改查的简单操作,具体使用请阅读参考资料. 使用步骤 一 ...
- 深度学习之卷积神经网络(CNN)详解与代码实现(二)
用Tensorflow实现卷积神经网络(CNN) 本文系作者原创,转载请注明出处:https://www.cnblogs.com/further-further-further/p/10737065. ...
- Redis分布式队列和缓存更新
原文链接:https://www.cnblogs.com/hua66/p/9600085.html 在使用Redis中,我们可能会遇到以下场景: 例如: 某用户向服务器中发送一个请求,服务器将用户请求 ...
- vue 日期时间过滤器
来自:https://blog.csdn.net/m0_37068028/article/details/72898154 侵删 来自:https://segmentfault.com/a/11900 ...