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 程序集注入(一)的更多相关文章

  1. # ASP.NET Core依赖注入解读&使用Autofac替代实现

    标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Aut ...

  2. 实现BUG自动检测 - ASP.NET Core依赖注入

    我个人比较懒,能自动做的事绝不手动做,最近在用ASP.NET Core写一个项目,过程中会积累一些方便的工具类或框架,分享出来欢迎大家点评. 如果以后有时间的话,我打算写一个系列的[实现BUG自动检测 ...

  3. [译]ASP.NET Core依赖注入深入讨论

    原文链接:ASP.NET Core Dependency Injection Deep Dive - Joonas W's blog 这篇文章我们来深入探讨ASP.NET Core.MVC Core中 ...

  4. asp.net core 依赖注入几种常见情况

    先读一篇注入入门 全面理解 ASP.NET Core 依赖注入, 学习一下基本使用 然后学习一招, 不使用接口规范, 直接写功能类, 一般情况下可以用来做单例. 参考https://www.cnblo ...

  5. ASP.NET Core依赖注入——依赖注入最佳实践

    在这篇文章中,我们将深入研究.NET Core和ASP.NET Core MVC中的依赖注入,将介绍几乎所有可能的选项,依赖注入是ASP.Net Core的核心,我将分享在ASP.Net Core应用 ...

  6. 自动化CodeReview - ASP.NET Core依赖注入

    自动化CodeReview系列目录 自动化CodeReview - ASP.NET Core依赖注入 自动化CodeReview - ASP.NET Core请求参数验证 我个人比较懒,能自动做的事绝 ...

  7. ASP.NET Core 依赖注入最佳实践——提示与技巧

    在这篇文章,我将分享一些在ASP.NET Core程序中使用依赖注入的个人经验和建议.这些原则背后的动机如下: 高效地设计服务和它们的依赖. 预防多线程问题. 预防内存泄漏. 预防潜在的BUG. 这篇 ...

  8. ASP.NET Core依赖注入最佳实践,提示&技巧

    分享翻译一篇Abp框架作者(Halil İbrahim Kalkan)关于ASP.NET Core依赖注入的博文. 在本文中,我将分享我在ASP.NET Core应用程序中使用依赖注入的经验和建议. ...

  9. ASP.NET Core依赖注入解读&使用Autofac替代实现【转载】

    ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Autofac实现和自定义实现扩展方法 3.1 安装Autof ...

  10. ASP.NET Core 依赖注入基本用法

    ASP.NET Core 依赖注入 ASP.NET Core从框架层对依赖注入提供支持.也就是说,如果你不了解依赖注入,将很难适应 ASP.NET Core的开发模式.本文将介绍依赖注入的基本概念,并 ...

随机推荐

  1. FFmpeg中的常见结构体

    代码基于FFmpeg5.0.1 目录 FFFormatContext AVFormatContext AVIOContext FFIOContext URLContext URLProtocol AV ...

  2. windows安装mysql8(5分钟)

    1.下载 MySQL https://dev.mysql.com/downloads/mysql/ 下载完成后,解压缩到你的目录里. 2.配置 MySQL 的配置文件 创建一个文件,名称为:my.in ...

  3. Linux下更新Python版本

    参考:安装图形化配置解析工具_LiteOS_编译和开发工具_Linux下的编译_搭建Linux编译环境_华为云 (huaweicloud.com) 系统:Centos7 $ uname -a Linu ...

  4. WPS相关技巧

    1 标题自动编号 首先,新建一个空白word,打开.点击默认的标题样式,可以看到并不会自动编号. 接下来,就设置如何自动编号.首先选择"编号". 然后,选择"多级编号&q ...

  5. Linux Shell命令提示样式修改

    对linux shell命令样式进行美化. 修改前的效果: 修改后的效果: 直接给出.bashrc脚本代码: 1 # ~/.bashrc: executed by bash(1) for non-lo ...

  6. fontawesome-webfont.woff:1 Failed to load resource: the server responded with a status of 404 ()

    fontawesome-webfont.woff2:1 Failed to load resource: the server responded with a status of 404 ()fon ...

  7. 燕千云 YQCloud 数智化业务服务管理平台 发布1.13版本

    2022年6月10日,燕千云 YQCloud 数智化业务服务管理平台发布1.13版本.本次燕千云1.13版本新增了远程桌面.知识库多人在线协作.移动端疫苗核酸信息管理.单据委托代理.技能管理.产品自助 ...

  8. 时间格式化转换及时间比较compareTo,Controller层接收参数格式化,从数据源头解决时间格式错误数据对接口的影响

    时间格式化转换及时间比较compareTo,Controller层接收参数格式化,从数据源头解决时间格式错误数据对接口的影响 /** * 时间格式的转换:在具体报错的地方做转换,可能不能从根本上面解决 ...

  9. 报错 ERR !npicode ELIFECYCLE dev: wue-cli-service serve

    在系统变量 Path 里面加上:%SystemRoot%\system32,关掉终端,重新启动项目.

  10. DHorse v1.5.1 发布,基于 k8s 的发布平台

    版本说明 新增特性 支持k8s的v1.30.x版本: 优化特性 优化回滚功能: 修复注册来源的回滚问题: 新增和修改应用时校验应用名: 升级kubernetes-client至v6.13.0: 调整部 ...