.NET6.0实现IOC容器
.NET6.0实现IOC容器
IOC的作用这里省略…只对如何使用进行说明。
1. 创建一个.NET6应用程序
这里使用 .NET6.0 WebAPI 应用
2. 声明接口
public interface IAuthService
{
bool CheckToken();
}
3. 实现接口
class AuthServiceImpl : IAuthService
{
public bool CheckToken()
{
Console.WriteLine("check token");
return true;
}
}
4. 配置IOC容器
下面是在 program 类中的代码
var services = new ServiceCollection();
services.AddSingleton<IAuthService, AuthServiceImpl>();
5. 获取服务
通过在 Controller的构造函数中注入IAuthService
private readonly IAuthService _service;
public WeatherForecastController(IAuthService service)
{
_service = service;
}
[HttpGet(Name = "test")]
public bool Get()
{
return _service.CheckToken();
}
启动后,通过swagger发起请求,验证接口。
基本IOC容器流程已实现。但是这样存在一个弊端,每个接口和实现都要在program中手动注册一遍,还要在Controller构造函数中进行依赖注入,有没有能自动实现注册代替program中的手动注册?
接下来,对上述流程进行改良。
6. 改良思路
定义一个AutowiredAttribute标记,通过Atrribute标记的方式,在实现类上标记其要实现的接口服务,然后实现一个服务加载类ServiceLoader,在这个类中反射获取所有具备AutoIocAttribute的实现类,然后注册到ServiceCollection中。
6.1 定义特性标记AutowiredAttribute
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class AutowiredAttribute : Attribute
{
/// <summary>
/// 接口
/// </summary>
public Type Iface { get; set; }
/// <summary>
/// 实现类名
/// </summary>
public string ImplClassName { get; set; }
public AutowiredAttribute(Type iface, [CallerMemberName] string implClassName = "")
{
Iface = iface;
ImplClassName = implClassName;
}
}
6.2 实现服务加载类
利用IServiceCollection作为服务容器
public class ServiceLoader
{
private static object _lock = new object();
private static AppRuntime _inst;
private readonly IServiceCollection _iocService = new ServiceCollection();
private readonly ICollection<Assembly> _iocAssembly = new HashSet<Assembly>();
private IServiceProvider _iocServiceProvider = null;
public static ServiceLoader Instance
{
get
{
if (_inst == null)
{
lock (_lock)
{
_inst = new ServiceLoader();
_inst.Startup(typeof(ServiceLoader).Assembly);
}
}
return _inst;
}
}
public T GetService<T>()
{
EnsureAutoIoc<T>();
return _iocServiceProvider.GetService<T>();
}
private void EnsureAutoIoc<T>()
{
Startup(typeof(T).Assembly);
}
public void Startup(Assembly ass)
{
if (_iocAssembly.Any(x => x == ass))
{
return;
}
_iocAssembly.Add(ass);
var types = ass.GetTypes().Where(x => x.GetCustomAttribute<AutowiredAttribute>() != null);
foreach (var item in types)
{
var autoIocAtt = item.GetCustomAttribute<AutowiredAttribute>();
AddTransient(autoIocAtt.Iface, item);
}
//_iocServiceProvider = _iocService.BuildServiceProvider();
Interlocked.Exchange(ref _iocServiceProvider, _iocService.BuildServiceProvider());
}
private void AddTransient(Type iface, Type impl)
{
_iocService.AddTransient(iface, impl);
}
}
6.3 在实现类加上标记
[Autowired(typeof(IAuthService))]
class AuthServiceImpl : IAuthService
{
public bool CheckToken()
{
Console.WriteLine("check token");
return true;
}
}
6.4 在 Controller 中调用
var svc = ServiceLoader.Instance.GetService<IAuthService>();
svc.CheckToken();
至此一个基本的完整IOC容器已实现。
.NET6.0实现IOC容器的更多相关文章
- .net core2.0下Ioc容器Autofac使用
.net core发布有一段时间了,最近两个月开始使用.net core2.0开发项目,大大小小遇到了一些问题.准备写个系列介绍一下是如何解决这些问题以及对应技术.先从IOC容器Autofac开始该系 ...
- Spring学习(四)在Web项目中实例化IOC容器
1.前言 前面我们讲到Spring在普通JAVA项目中的一些使用.本文将介绍在普通的Web项目中如何实例化Spring IOC容器.按照一般的思路.如果在Web中实例化Ioc容器.这不得获取Conte ...
- 从0开始搭建一个IoC容器(C#版)
网址:https://blog.csdn.net/wangyahua1234/article/details/100619695 目录 1. IoC简介 2. Tiny版IoC的功能 3. Tiny版 ...
- 【.NET6+WPF】WPF使用prism框架+Unity IOC容器实现MVVM双向绑定和依赖注入
前言:在C/S架构上,WPF无疑已经是"桌面一霸"了.在.NET生态环境中,很多小伙伴还在使用Winform开发C/S架构的桌面应用.但是WPF也有很多年的历史了,并且基于MVVM ...
- IL实现简单的IOC容器
既然了解了IL的接口和动态类之间的知识,何不使用进来项目实验一下呢?而第一反应就是想到了平时经常说的IOC容器,在园子里搜索了一下也有这类型的文章http://www.cnblogs.com/kkll ...
- 通过中看不中用的代码分析Ioc容器,依赖注入....
/** * 通过生产拥有超能力的超人实例 来理解IOC容器 */ //超能力模组接口 interface SuperModuleInterface{ public function activate( ...
- .net自带的IOC容器MEF使用
IOC能做什么 IoC 不是一种技术,只是一种思想,一个重要的面向对象编程的法则,它能指导我们如何设计出松耦合.更优良的程序. 控制反转: 将控制权移交给第三方容器 new 操作 依赖注入: 在程序 ...
- 自定义模拟一个Spring IOC容器
一.模拟一个IOC容器: 介绍:现在,我们准备使用一个java project来模拟一个spring的IOC容器创建对象的方法,也就是不使用spring的jar自动帮助我们创建对象,而是通过自己手动书 ...
- IoC原理-使用反射/Emit来实现一个最简单的IoC容器
从Unity到Spring.Net,到Ninject,几年来陆陆续续用过几个IoC框架.虽然会用,但也没有一直仔细的研究过IoC实现的过程.最近花了点时间,下了Ninject的源码,研究了一番,颇有收 ...
- Spring框架IOC容器和AOP解析
主要分析点: 一.Spring开源框架的简介 二.Spring下IOC容器和DI(依赖注入Dependency injection) 三.Spring下面向切面编程(AOP)和事务管理配置 一.S ...
随机推荐
- weex 开发APP 多行文本溢出处理
weex中文字溢出不能使用常规的overflow:hidden 如: .text { overflow: hidden; text-overflow: ellipsis; white-space: n ...
- k8s实战案例之部署Zookeeper集群
1.Zookeeper简介 zookeeper是一个开源的分布式协调服务,由知名互联网公司Yahoo创建,它是Chubby的开源实现:换句话讲,zookeeper是一个典型的分布式数据一致性解决方案, ...
- WPF入门教程系列二十八 ——DataGrid使用示例MVVM模式(6)
WPF入门教程系列目录 WPF入门教程系列二--Application介绍 WPF入门教程系列三--Application介绍(续) WPF入门教程系列四--Dispatcher介绍 WPF入门教程系 ...
- instance norm
与Batch Norm加快计算收敛不同, IN是在[1]中提出的,目的是提高style transfer的表现. 计算如下: \[IN(x)=\gamma (\frac{x-\mu(x)}{\sigm ...
- 自然语言处理 Paddle NLP - 任务式对话系统-理论
什么是任务型对话: 任务型:用于帮助用户完成某领域的特定任务,例如订餐.查天气.订票等 闲聊型:也称作开放域对话系统,目标是让用户持续的参与到交互过程,提供情感陪伴 问答型:提供知识满足,具体类型比较 ...
- Spring Loaded代码热更新实践和原理分析
1.引言 开发者在编码效率和快速迭代中的痛点场景包括: 修改代码后,需要频繁重启应用,导致开发效率低下: 实时调试时,不能立即看到代码修改的结果: 大型项目中,重启的时间成本较高. 针对这些问题,本文 ...
- 运行C时报错:relocation truncated to fit: R_X86_64_PC32 against undefined symbol `WinMain‘ collect2: error
写C时,遇到报错 [Running] cd "d:\考研\408\LeranC\Code\GramForC\" && gcc 01data_types.c -o 0 ...
- Djiango 创建迁移项报错query = query.decode(errors='replace') AttributeError: 'str' object has no attribute 'decode'
在终端命令行创建迁移项 输入(python manage.py makemigrations) 或(python manage.py migrate)时出现报错信息:Traceback (most r ...
- 【HTML】Echart图表
layui-echarts 简介 基于layui 实现的 echart 图表 Echart 官网 示例 Echart示例 下载Echart Echart下载 我们选择最下面的在线定制 我这里就按照它默 ...
- sql相关小知识—
数据库系统达到了数据独立性是因为采用了三级模式结构 人们为数据库设计了一个严谨的体系结构,数据库领域公认的标准结构是三级模式结构,它包括外模式.概念模式.内模式,有效地组织.管理数据,提高了数据库的逻 ...