ASP.NET Core 程序集注入(一)
1.创建【特性】用于标注依赖注入
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic; namespace Util.Attributes
{
/// <summary>
/// 标注要运用DI的类 被此属性标注的类 要被注册到依赖注入容器中 并且可以指定类要映射的接口或者类
/// 此属性只能运用于类,并且此属性不能继承
/// </summary>
[AttributeUsage(AttributeTargets.Class,Inherited =false)]
public class UseDIAttribute:Attribute
{
//Targets用于指示 哪些接口或者类 要被 "被属性修饰了的类" 进行依赖注入
public List<Type> TargetTypes=new List<Type>();
public ServiceLifetime lifetime;
public UseDIAttribute(ServiceLifetime argLifetime,params Type[] argTargets)
{
lifetime = argLifetime;
foreach (var argTarget in argTargets)
{
TargetTypes.Add(argTarget);
}
} public List<Type> GetTargetTypes()
{
return TargetTypes;
}
public ServiceLifetime Lifetime
{
get
{
return this.lifetime;
}
}
}
}
2.对程序集中要注入的类进行标记
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Threading.Tasks;
using User.Domain;
using User.Domain.POCOModels;
using Util.Attributes; namespace DDD.Repositories.UserRepositories
{
[UseDI(ServiceLifetime.Scoped,typeof(ILoginRepository))]
public class LoginEFCoreRepository:ILoginRepository
{
private readonly DbContext dbContext;
public LoginEFCoreRepository(DbContext dbContext)
{
this.dbContext = dbContext;
}
}
}

3.为IserviceCollection扩展一个方法 可以实现对程序集进行操作
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Util.Attributes; namespace Util.DIPlugin
{
public static class NetCoreDIModuleRegister
{
/// <summary>
/// 自动注册服务
/// </summary>
/// <param name="services">注册服务的集合(向其中注册)</param>
/// <param name="ImplementationType">要注册的类型</param>
public static void AutoRegisterService(this IServiceCollection services, Type ImplementationType)
{
//获取类型的 UseDIAttribute 属性 对应的对象
UseDIAttribute attr = ImplementationType.GetCustomAttribute(typeof(UseDIAttribute)) as UseDIAttribute;
////获取类实现的所有接口
//Type[] types = ImplementationType.GetInterfaces();
List<Type> types = attr.GetTargetTypes();
var lifetime = attr.Lifetime;
//遍历类实现的每一个接口
foreach (var t in types)
{
//将类注册为接口的实现-----但是存在一个问题,就是担心 如果一个类实现了IDisposible接口 担心这个类变成了这个接口的实现
ServiceDescriptor serviceDescriptor = new ServiceDescriptor(t, ImplementationType, lifetime);
services.Add(serviceDescriptor);
}
}
/// <summary>
/// 根据程序集的名字获取程序集中所有的类型集合
/// </summary>
/// <param name="AssemblyName">程序集名字</param>
/// <returns>类型集合</returns>
public static Type[] GetTypesByAssemblyName(String AssemblyName)
{
Assembly assembly = Assembly.Load(AssemblyName);
return assembly.GetTypes();
} #region 将程序集中的所有符合条件的类型全部注册到 IServiceCollection 中 重载1
/// <summary>
/// 将程序集中的所有符合条件的类型全部注册到 IServiceCollection 中
/// </summary>
/// <param name="services">IServiceCollection</param>
/// <param name="AassemblyName">程序集名字</param>
public static void AutoRegisterServicesFromAssembly(this IServiceCollection services, string AassemblyName)
{
//根据程序集的名字 获取程序集中所有的类型
Type[] types = GetTypesByAssemblyName(AassemblyName);
//过滤上述程序集 首先按照传进来的条件进行过滤 接着要求Type必须是类,而且不能是抽象类
IEnumerable<Type> _types = types.Where(t => t.IsClass && !t.IsAbstract);
foreach (var t in _types)
{
IEnumerable<Attribute> attrs = t.GetCustomAttributes();
//遍历类的所有特性
foreach (var attr in attrs)
{
//如果在其特性中发现特性是 UseDIAttribute 特性 就将这个类注册到DI容器中去
//并跳出当前的循环 开始对下一个类进行循环
if (attr is UseDIAttribute)
{
services.AutoRegisterService(t);
break;
}
}
}
}
#endregion #region 将程序集中的所有符合条件的类型全部注册到 IServiceCollection 中 重载2
/// <summary>
/// 将程序集中的所有符合条件的类型全部注册到 IServiceCollection 中
/// </summary>
/// <param name="services">IServiceCollection</param>
/// <param name="AassemblyName">程序集名字</param>
/// <param name="wherelambda">过滤类型的表达式</param>
public static void AutoRegisterServicesFromAssembly(this IServiceCollection services,
string AassemblyName, Func<Type, bool> wherelambda)
{
//根据程序集的名字 获取程序集中所有的类型
Type[] types = GetTypesByAssemblyName(AassemblyName);
//过滤上述程序集 首先按照传进来的条件进行过滤 接着要求Type必须是类,而且不能是抽象类
IEnumerable<Type> _types = types.Where(wherelambda).Where(t => t.IsClass && !t.IsAbstract);
foreach (var t in _types)
{
IEnumerable<Attribute> attrs = t.GetCustomAttributes();
//遍历类的所有特性
foreach (var attr in attrs)
{
//如果在其特性中发现特性是 UseDIAttribute 特性 就将这个类注册到DI容器中去
//并跳出当前的循环 开始对下一个类进行循环
if (attr is UseDIAttribute)
{
services.AutoRegisterService(t);
break;
}
}
}
}
#endregion
}
}
4.在webapi的startup.cs类中注册 需要处理的程序集:

ASP.NET Core 程序集注入(一)的更多相关文章
- # ASP.NET Core依赖注入解读&使用Autofac替代实现
标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Aut ...
- 实现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应用程序中使用依赖注入的经验和建议. ...
- ASP.NET Core依赖注入解读&使用Autofac替代实现【转载】
ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Autofac实现和自定义实现扩展方法 3.1 安装Autof ...
- ASP.NET Core 依赖注入基本用法
ASP.NET Core 依赖注入 ASP.NET Core从框架层对依赖注入提供支持.也就是说,如果你不了解依赖注入,将很难适应 ASP.NET Core的开发模式.本文将介绍依赖注入的基本概念,并 ...
随机推荐
- 深入剖析Arthas源码
一. 前言 Arthas 相信大家已经不陌生了,肯定用过太多次了,平时说到 Arthas 的时候都知道是基于Java Agent的,那么他具体是怎么实现呢,今天就一起来看看. 首先 Arthas 是在 ...
- WPF显示网络图片的几种方法
1.利用数据流 1 Image img; 2 byte[] btyarray = GetImageFromResponse(imageUrl); 3 4 //字节数据转流 5 MemoryStream ...
- svg动画导致持续占用CPU
1.在一次性能优化中突然发现一个svg矢量图动画导致CPU持续占用的问题,该svg在web中使用, 即使webview释放之后,CPU依然占用达到10%,6s+上测试结果 svg如下所示: <s ...
- IOS Video Tool Box后台解码失败
---恢复内容开始--- 1.VideoToolBox硬件解码H264流的过程中,如果App从前台按Home键进入后台,会立马产生一个-12903的错误 如果这个时候重置解码器,继续解码,会遇到 - ...
- 头条abogus与Js补环境代理Upgrade!
声明 本文章中所有内容仅供学习交流,抓包内容.敏感网址.数据接口均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关,若有侵权,请联系我立即删除! 目标网站 aHR0cHM6 ...
- vue3 KeepAlive
在Vue.js 3中,<keep-alive> 是一个抽象组件,用于保留其子组件状态,防止在切换组件时销毁它们.这对于在页面间切换时保留组件的状态或避免重复渲染特定组件非常有用.<k ...
- vue单个插槽
当子组件模板只有一个没有属性的插槽时,父组件传入的整个内容片段将插入到插槽所在的 DOM 位置,并替换掉插槽标签本身. # 子组件 <div> <h2>我是子组件的标题< ...
- Easysearch:语义搜索、知识图和向量数据库概述
什么是语义搜索? 语义搜索是一种使用自然语言处理算法来理解单词和短语的含义和上下文以提供更准确的搜索结果的搜索技术.旨在更好地理解用户的意图和查询内容,而不仅仅是根据关键词匹配,还通过分析查询的语义和 ...
- FlashDuty Changelog 2023-09-21 | 自定义字段和开发者中心
FlashDuty:一站式告警响应平台,前往此地址免费体验! 自定义字段 FlashDuty 已支持接入大部分常见的告警系统,我们将推送内容中的大部分信息放到了 Lables 进行展示.尽管如此,我们 ...
- NFS练习
NFS练习题 1.开放/nfs/share目录,提供给 任意用户 只读(/etc/exports ro) 查询 1.任意客户端2.任意的用户 服务端 showmout exportfs system ...