翼度科技»论坛 编程开发 .net 查看内容

精准掌握.NET依赖注入:DI自动注册服务轻松搞定

10

主题

10

帖子

30

积分

新手上路

Rank: 1

积分
30
 
概述:.NET依赖注入(DI)通过反射自动注册服务,示例展示了注册指定类、带特性类、项目下所有接口实现的类。简化配置,提高可维护性。
在.NET中,进行依赖注入(DI)的自动注册,可以通过反射机制和程序集扫描来实现。以下是详细的步骤以及相应的C#源代码示例,包括注册指定类、注册带有自定义特性的类、以及注册项目下所有带有接口实现的类(项目下的所有接口):
步骤1:创建接口和实现类
  1. // 接口1
  2. public interface IService1
  3. {
  4.     void PerformService1();
  5. }
  6. // 接口2
  7. public interface IService2
  8. {
  9.     void PerformService2();
  10. }
  11. // 实现类1,实现IService1
  12. public class MyService1 : IService1
  13. {
  14.     public void PerformService1()
  15.     {
  16.         Console.WriteLine("Service 1 performed.");
  17.     }
  18. }
  19. // 实现类2,实现IService2
  20. [CustomRegistration] // 带有自定义特性
  21. public class MyService2 : IService2
  22. {
  23.     public void PerformService2()
  24.     {
  25.         Console.WriteLine("Service 2 performed.");
  26.     }
  27. }
  28. // 实现类3,实现IService1和IService2
  29. public class MyService3 : IService1, IService2
  30. {
  31.     public void PerformService1()
  32.     {
  33.         Console.WriteLine("Service 3 (Service 1 part) performed.");
  34.     }
  35.     public void PerformService2()
  36.     {
  37.         Console.WriteLine("Service 3 (Service 2 part) performed.");
  38.     }
  39. }
复制代码
步骤2:创建自定义特性
  1. // 自定义特性
  2. [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
  3. sealed class CustomRegistrationAttribute : Attribute
  4. {
  5. }
复制代码
步骤3:创建自动注册方法
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using Microsoft.Extensions.DependencyInjection;
  5. class Program
  6. {
  7.     static void Main()
  8.     {
  9.         // 创建服务集合
  10.         var services = new ServiceCollection();
  11.         // 步骤4:注册指定类
  12.         services.AddTransient<MyService1>();
  13.         // 步骤5:注册带有自定义特性的类
  14.         RegisterClassesWithAttribute<CustomRegistrationAttribute>(services);
  15.         // 步骤6:注册项目下所有带有接口实现的类(项目下的所有接口)
  16.         RegisterAllImplementationsOfInterfaces(services);
  17.         // 构建服务提供程序
  18.         var serviceProvider = services.BuildServiceProvider();
  19.         // 步骤7:使用注册的服务
  20.         var myService1 = serviceProvider.GetService<MyService1>();
  21.         myService1.PerformService1();
  22.         var myService2 = serviceProvider.GetService<MyService2>();
  23.         myService2.PerformService2();
  24.         var myService3 = serviceProvider.GetService<MyService3>();
  25.         myService3.PerformService1();
  26.         myService3.PerformService2();
  27.     }
  28.     // 自动注册带有指定特性的类
  29.     static void RegisterClassesWithAttribute<TAttribute>(IServiceCollection services)
  30.         where TAttribute : Attribute
  31.     {
  32.         // 获取当前程序集
  33.         var assembly = Assembly.GetExecutingAssembly();
  34.         // 获取带有指定特性的所有类
  35.         var attributedTypes = assembly.GetTypes()
  36.             .Where(type => type.GetCustomAttributes(typeof(TAttribute), true).Any() && type.IsClass);
  37.         // 注册这些类
  38.         foreach (var attributedType in attributedTypes)
  39.         {
  40.             services.AddTransient(attributedType);
  41.         }
  42.     }
  43.     // 自动注册项目下所有带有接口实现的类(项目下的所有接口)
  44.     static void RegisterAllImplementationsOfInterfaces(IServiceCollection services)
  45.     {
  46.         // 获取当前程序集
  47.         var assembly = Assembly.GetExecutingAssembly();
  48.         // 获取项目下所有接口
  49.         var interfaceTypes = assembly.GetTypes()
  50.             .Where(type => type.IsInterface);
  51.         // 获取实现了这些接口的所有类
  52.         var implementationTypes = assembly.GetTypes()
  53.             .Where(type => interfaceTypes.Any(interfaceType => interfaceType.IsAssignableFrom(type)) && type.IsClass);
  54.         // 注册这些类
  55.         foreach (var implementationType in implementationTypes)
  56.         {
  57.             services.AddTransient(implementationType);
  58.         }
  59.     }
  60. }
复制代码
在上述代码中:

  • 使用AddTransient方法注册了特定的MyService1类。
  • 使用RegisterClassesWithAttribute方法注册了带有CustomRegistrationAttribute特性的类。这里使用了反射机制来动态获取所有带有指定特性的类的类型,并将它们注册到DI容器中。
  • 使用RegisterAllImplementationsOfInterfaces方法注册了项目下所有实现接口的类。
请确保在项目中引用了
Microsoft.Extensions.DependencyInjection相关的包。这是一个基本的示例,实际应用中可能需要更复杂的配置,具体取决于项目的需求。
 


来源:https://www.cnblogs.com/hanbing81868164/archive/2023/12/19/17912799.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具