netcore依赖注入通过反射简化
aspnetcore里面用到许多的service,好多业务代码都要通过Service.AddScoped、Singleton、Transient等注入进去,类太多了写起来和管理起来都很麻烦,所以借鉴了一下github上面的项目稍微删减了一下下,最后会给出参考链接和git源代码。
项目结构如下,

这里面有些约定的东西一定要遵守,否则会出错,还有webapi必须要引用business和ibusiness,只引用ibusiness是不行的。
核心代码如下:
1 using Microsoft.Extensions.DependencyInjection;
2 using System;
3 using System.Collections.Generic;
4 using System.Linq;
5 using System.Text;
6 using System.Threading.Tasks;
7 using My.Project.Ioc.Core.IService;
8
9 namespace My.Project.Ioc.Core.Extensions
10 {
11 public static partial class ServiceExtensions
12 {
13 /// <summary>
14 /// 自动注入拥有ITransientDependency,IScopeDependency或ISingletonDependency的类
15 /// </summary>
16 /// <param name="services">服务集合</param>
17 /// <returns></returns>
18 public static IServiceCollection AddFxServices(this IServiceCollection services)
19 {
20 Dictionary<Type, ServiceLifetime> lifeTimeMap = new Dictionary<Type, ServiceLifetime>
21 {
22 { typeof(ITransientDependency), ServiceLifetime.Transient},
23 { typeof(IScopedDependency),ServiceLifetime.Scoped},
24 { typeof(ISingletonDependency),ServiceLifetime.Singleton}
25 };
26
27 GlobalData.AllFxTypes.ForEach(aType =>
28 {
29 lifeTimeMap.ToList().ForEach(aMap =>
30 {
31 var theDependency = aMap.Key;
32 if (theDependency.IsAssignableFrom(aType) && theDependency != aType && !aType.IsAbstract && aType.IsClass)
33 {
34 //注入实现
35 services.Add(new ServiceDescriptor(aType, aType, aMap.Value));
36
37 var interfaces = GlobalData.AllFxTypes.Where(x => x.IsAssignableFrom(aType) && x.IsInterface && x != theDependency).ToList();
38 //有接口则注入接口
39 if (interfaces.Count > 0)
40 {
41 interfaces.ForEach(aInterface =>
42 {
43 services.Add(new ServiceDescriptor(aInterface, serviceProvider => serviceProvider.GetService(aType), aMap.Value));
44 });
45 }
46 //无接口则注入自己
47 else
48 {
49 services.Add(new ServiceDescriptor(aType, aType, aMap.Value));
50 }
51 }
52 });
53 });
54
55 return services;
56 }
57 }
58 }
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Linq;
5 using System.Reflection;
6 using System.Text;
7 using System.Threading.Tasks;
8
9 namespace My.Project.Ioc.Core
10 {
11 public static class GlobalData
12 {
13 static GlobalData()
14 {
15 string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
16 AllFxAssemblies = Directory.GetFiles(rootPath, "*.dll")
17 .Where(x => new FileInfo(x).Name.Contains(FXASSEMBLY_PATTERN))
18 .Select(x => Assembly.LoadFrom(x))
19 .Where(x => !x.IsDynamic)
20 .ToList();
21
22 AllFxAssemblies.ForEach(aAssembly =>
23 {
24 try
25 {
26 AllFxTypes.AddRange(aAssembly.GetTypes());
27 }
28 catch
29 {
30
31 }
32 });
33 }
34
35 /// <summary>
36 /// 解决方案程序集匹配名
37 /// </summary>
38 public const string FXASSEMBLY_PATTERN = "My.Project.Ioc";
39
40 /// <summary>
41 /// 解决方案所有程序集
42 /// </summary>
43 public static readonly List<Assembly> AllFxAssemblies;
44
45 /// <summary>
46 /// 解决方案所有自定义类
47 /// </summary>
48 public static readonly List<Type> AllFxTypes = new List<Type>();
49 }
50 }
非核心代码如下:
参考项目Coldairarrow/Colder.Admin.AntdVue: Admin Fx Based On .NET 5 + Ant Design Vue (github.com) ,有兴趣的可以研究下非常不错。当然里面关于aop和缓存方面我有另外的项目例子可以加进去改造exercise/netcore.demo/AspNetCoreEntityFrameWork at master · liuzhixin405/exercise (github.com)

netcore依赖注入通过反射简化的更多相关文章
- Laravel框架下容器Container 的依赖注入和反射应用
依赖注入,简单说是把类里头依赖的对象,置于类外头,即客户端调用处.相当于把类与类解耦. 一个简单的例子: class A { public function __construct() { // 这种 ...
- C#反射与特性(六):设计一个仿ASP.NETCore依赖注入Web
目录 1,编写依赖注入框架 1.1 路由索引 1.2 依赖实例化 1.3 实例化类型.依赖注入.调用方法 2,编写控制器和参数类型 2.1 编写类型 2.2 实现控制器 3,实现低配山寨 ASP.NE ...
- Asp.NetCore依赖注入和管道方式的异常处理及日志记录
前言 在业务系统,异常处理是所有开发人员必须面对的问题,在一定程度上,异常处理的能力反映出开发者对业务的驾驭水平:本章将着重介绍如何在 WebApi 程序中对异常进行捕获,然后利用 Nlog ...
- NetCore 依赖注入之服务之间的依赖关系
简单介绍,直接官方文档 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection?view=aspn ...
- c# 依赖注入之---反射(转)
详细请看http://www.cnblogs.com/leoo2sk/archive/2009/06/17/1504693.html 定义一个接口,和两个类(实现该接口) IButton: using ...
- .netcore中的依赖注入
IOC.DI相关概念的理解 1.依赖:简单的讲就是"引用到".例如AccountController.cs引用到IAccountService.cs,那么AccountContro ...
- PHP 在Swoole中使用双IoC容器实现无污染的依赖注入
简介: 容器(container)技术(可以理解为全局的工厂方法), 已经是现代项目的标配. 基于容器, 可以进一步实现控制反转, 依赖注入. Laravel 的巨大成功就是构建在它非常强大的IoC容 ...
- NetCore+Dapper WebApi架构搭建(四):仓储的依赖注入
上一节我们讲到实体,仓储接口和仓储接口的实现需要遵循约定的命名规范,不仅是规范,而且为了依赖注入,现在我们实现仓储的依赖注入 在NetCore WebApi项目中新添加一个文件夹(Unit),当然你也 ...
- 采用dom4j和反射模拟Spring框架的依赖注入功能
Spring的依赖注入是指将对象的创建权交给Spring框架,将对象所依赖的属性注入进来的行为.在学习了dom4j后,其实也可以利用dom4j和反射做一个小Demo模拟Spring框架的这种功能.下面 ...
- 基于反射的通过set方法的依赖注入,可以看成一种设计模式,自己来用
非常好用,在properties文件中配置字符串和类名之间的对应,在程序里读取文件,找到类名,通过反射,达到调用set方法的目的,然后直接将自己的指向其他类的对象的引用赋值,指向实体对象. 比如use ...
随机推荐
- Informix日志报错:Could not do a physical-order read to fetch netxt row
jmeter请求接口,1线程不报错,2线程及以上报错"无法执行查询",看后台日志,报错Could not do a physical-order read to fetch net ...
- FPGA 原语之一位全加器
FPGA原语之一位全加器 1.实验原理 一位全加器,三个输入,两个输出.进位输出Cout=AB+BC+CA,本位输出S=A异或B异或C.实验中采用三个与门.一个三输入或门(另外一个是两个或门,功能一致 ...
- KingbaseES V8R3集群运维案例之---failover故障处理
案例说明: 此案例,为KingbaseES V8R3集群failover切换时,通用的故障处理方式.通过对failover.log和recovery.log日志的解读,让大家了解KingbaseE ...
- 基于spring-boot、grpc、zookeeper的分布式微服务架构
总览: 开源.高性能.多语言.跨平台.易扩展rpc框架 . Protocol Buffers 使用 默认使用 protocol buffers,Google 开源的成熟序列化机制: 文件格式:.pro ...
- C++ 编程必备:对象生命周期管理的最佳实践
在C++中,对象的生命周期是指对象存在的时间段,从对象创建到对象销毁的整个过程.正确地管理对象的生命周期是编写高效.可靠C++代码的关键之一 对象的创建 在C++中,对象可以通过三种方式创建:静态分配 ...
- 将Map中对应的key和value赋值到对象中
BeanUtils位于import org.apache.commons.beanutils.BeanUtils包下 其使用方法: Map<String, Object> objectMa ...
- std::thread 六:多线程&单例类
为了避免单例类在多线程中重复的创建,下面提供了两种解决方法: 1.互斥锁+双重检查 2.std::call_once() 方法一:互斥锁+双重检查 #include <iostream> ...
- 编译安装openGauss 3.0.0
编译安装 openGauss 3.0.0 环境检查 1.1 检查 OS 版本 openGauss支持的操作系统: CentOS 7.6(x86 架构) openEuler-20.03-LTS(aarc ...
- HarmonyOS实现表单页面的输入,必填校验和提交
一. 样例介绍 本篇Codelab基于input组件.label组件和dialog组件,实现表单页面的输入.必填校验和提交: 1. 为input组件设置不同类型(如:text,email,date等 ...
- HarmonyOS 极客马拉松2023 正式启动,诚邀极客们用键盘码出无限可能!
原文:https://mp.weixin.qq.com/s/p2yIs0rMmDE2BwhzsAtr7A,点击链接查看更多技术内容. 2023年6月15日, HarmonyOS极客马拉松2023开 ...