-
精准掌握.NET依赖注入:DI自动注册服务轻松搞定
概述:.NET依赖注入(DI)通过反射自动注册服务,示例展示了注册指定类、带特性类、项目下所有接口实现的类。简化配置,提高可维护性。
在.NET中,进行依赖注入(DI)的自动注册,可以通过反射机制和程序集扫描来实现。以下是详细的步骤以及相应的C#源代码示例,包括注册指定类、注册带有自定义特性的类、以及注册项目下所有带有接口实现的类(项目下的所有接口):
步骤1:创建接口和实现类
// 接口1
public interface IService1
{
void PerformService1();
}
// 接口2
public interface IService2
{
void PerformService2();
}
// 实现类1,实现IService1
public class MyService1 : IService1
{
public void PerformService1()
{
Console.WriteLine("Service 1 performed.");
}
}
// 实现类2,实现IService2
[CustomRegistration] // 带有自定义特性
public class MyService2 : IService2
{
public void PerformService2()
{
Console.WriteLine("Service 2 performed.");
}
}
// 实现类3,实现IService1和IService2
public class MyService3 : IService1, IService2
{
public void PerformService1()
{
Console.WriteLine("Service 3 (Service 1 part) performed.");
}
public void PerformService2()
{
Console.WriteLine("Service 3 (Service 2 part) performed.");
}
}
步骤2:创建自定义特性
// 自定义特性
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
sealed class CustomRegistrationAttribute : Attribute
{
}
步骤3:创建自动注册方法
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
class Program
{
static void Main()
{
// 创建服务集合
var services = new ServiceCollection();
// 步骤4:注册指定类
services.AddTransient<MyService1>();
// 步骤5:注册带有自定义特性的类
RegisterClassesWithAttribute<CustomRegistrationAttribute>(services);
// 步骤6:注册项目下所有带有接口实现的类(项目下的所有接口)
RegisterAllImplementationsOfInterfaces(services);
// 构建服务提供程序
var serviceProvider = services.BuildServiceProvider();
// 步骤7:使用注册的服务
var myService1 = serviceProvider.GetService<MyService1>();
myService1.PerformService1();
var myService2 = serviceProvider.GetService<MyService2>();
myService2.PerformService2();
var myService3 = serviceProvider.GetService<MyService3>();
myService3.PerformService1();
myService3.PerformService2();
}
// 自动注册带有指定特性的类
static void RegisterClassesWithAttribute<TAttribute>(IServiceCollection services)
where TAttribute : Attribute
{
// 获取当前程序集
var assembly = Assembly.GetExecutingAssembly();
// 获取带有指定特性的所有类
var attributedTypes = assembly.GetTypes()
.Where(type => type.GetCustomAttributes(typeof(TAttribute), true).Any() && type.IsClass);
// 注册这些类
foreach (var attributedType in attributedTypes)
{
services.AddTransient(attributedType);
}
}
// 自动注册项目下所有带有接口实现的类(项目下的所有接口)
static void RegisterAllImplementationsOfInterfaces(IServiceCollection services)
{
// 获取当前程序集
var assembly = Assembly.GetExecutingAssembly();
// 获取项目下所有接口
var interfaceTypes = assembly.GetTypes()
.Where(type => type.IsInterface);
// 获取实现了这些接口的所有类
var implementationTypes = assembly.GetTypes()
.Where(type => interfaceTypes.Any(interfaceType => interfaceType.IsAssignableFrom(type)) && type.IsClass);
// 注册这些类
foreach (var implementationType in implementationTypes)
{
services.AddTransient(implementationType);
}
}
}
在上述代码中:
- 使用AddTransient方法注册了特定的MyService1类。
- 使用RegisterClassesWithAttribute方法注册了带有CustomRegistrationAttribute特性的类。这里使用了反射机制来动态获取所有带有指定特性的类的类型,并将它们注册到DI容器中。
- 使用RegisterAllImplementationsOfInterfaces方法注册了项目下所有实现接口的类。
请确保在项目中引用了
Microsoft.Extensions.DependencyInjection相关的包。这是一个基本的示例,实际应用中可能需要更复杂的配置,具体取决于项目的需求。
出处:https://www.cnblogs.com/hanbing81868164/p/17912799.html
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式