自动注入类

1、通过序反射获取父类接口

 1 namespace Service.Basic
 2 {
 3     using System;
 4     using System.Linq;
 5     using Microsoft.Extensions.DependencyInjection;
 6 
 7     /// <summary>
 8     /// 自动注入类
 9     /// </summary>
10     public static class AutoDI
11     {
12         /// <summary>
13         /// 注入来源类型下的所有类型
14         /// </summary>
15         /// <param name="services">服务配置接口</param>
16         /// <param name="source">接口实现类的类型</param>
17         /// <returns>注入完的服务配置</returns>
18         public static IServiceCollection AutoInjection(this IServiceCollection services, Type source)
19         {
20             // 获取实现了接口IDenpendency和IDenpendcySingleton的程序集
21             var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(source)));
22 
23             // class的程序集
24             var implementTypes = allTypes.Where(x => x.IsClass).ToArray();
25 
26             // 接口的程序集
27             var interfaceTypes = allTypes.Where(x => x.IsInterface).ToArray();
28             foreach (var implementType in implementTypes)
29             {
30                 var interfaces = interfaceTypes.Where(x => x.IsAssignableFrom(implementType)).ToList();
31 
32                 foreach (var inter in interfaces)
33                 {
34                     // class有接口,用接口注入
35                     if (inter != null)
36                     {
37                         // 判断用什么方式注入
38                         if (inter.GetInterfaces().Contains(source))
39                         {
40                             services.AddScoped(inter, implementType);
41                         }
42                     }
43                 }
44 
45                 if (implementType.GetInterfaces().Contains(source))
46                 {
47                     services.AddTransient(implementType);
48                 }
49             }
50 
51             return services;
52         }
53     }
54 }
View Code

 

 

2、定义父类接口

1 /// <summary>
2     /// 通用接口
3     /// </summary>
4     public interface IDenpendency
5     {
6     }
View Code

 

3、父类接口用法

 1     /// <summary>
 2     /// 演示接口
 3     /// </summary>
 4     public interface IDemo : IDenpendency
 5     {
 6         /// <summary>
 7         /// 获取当前时间
 8         /// </summary>
 9         /// <returns>返回当前时间</returns>
10         Task<DateTime> GetDateTimeNow();
11     }
View Code

 

4、在程序启动注入父类接口

1             // 自动注入接口/类
2             services.AutoInjection(typeof(IDenpendency));

 

posted @ 2022-06-15 15:06  个人天使  阅读(27)  评论(0编辑  收藏  举报