Asp.net Core 中一键注入接口

Asp.net Core 中一键注入接口

前言

在之前开发Asp.Net Core程序时遇到接口需要一个一个的注入到Services中,当有非常多的接口需要注入时会显得代码成为了一座山,这里记录一下如何通过接口的命名一键自动注入.

准备

IDE: Visual studio 2022

.Net版本:.Net 8

开始

首先是接口的命名需要规范,列如接口命名为TestDao,实现类命名为TestDaoImpl,这里就以DaoDaoImpl来做示范.

新建一个类,命名为ServiceCollectionExtensions,内容如下:

csharp 复制代码
        public static IServiceCollection AddDaosWithConvention(this IServiceCollection services, Assembly assembly)
        {
            var interfaceSuffix = "Dao"; // 接口命名结尾
            var implementationSuffix = "DaoImpl";// 实现类命名结尾
			
			// 通过反射的机制来寻找所有的接口命名符合interfaceSuffix 结尾的
            var interfaceTypes = assembly.GetTypes()
                                         .Where(t => t.IsInterface && t.Name.EndsWith(interfaceSuffix))
                                         .ToArray();
			// 通过反射的机制来寻找所有的实现类命名符合interfaceSuffix 结尾的
            var types = assembly.GetTypes()
                                .Where(t => t.IsClass && !t.IsAbstract && t.Name.EndsWith(implementationSuffix))
                                .ToList();
			
			// 使用AddScoped注入所有符合的接口与实现类
            foreach (var interfaceType in interfaceTypes)
            {
                foreach (var type in types)
                {
                    var interfaceName = type.GetInterfaces()
                                            .FirstOrDefault(i => i.Name == interfaceType.Name)
                                            ?.Name;

                    if (interfaceName != null)
                    {
                        services.AddScoped(interfaceType, type);
                    }
                }
            }

            return services;
        }

使用

Program.cs文件中添加:

csharp 复制代码
builder.Services.AddDaosWithConvention(Assembly.GetExecutingAssembly());

当上述配置完成后,在创建完接口与实现类后可以直接引用,不需要再去注册.

相关推荐
XMYX-04 小时前
Spring Boot + Prometheus 实现应用监控(基于 Actuator 和 Micrometer)
spring boot·后端·prometheus
@yanyu6665 小时前
springboot实现查询学生
java·spring boot·后端
酷爱码6 小时前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
AI小智6 小时前
Google刀刃向内,开源“深度研究Agent”:Gemini 2.5 + LangGraph 打造搜索终结者!
后端
java干货7 小时前
虚拟线程与消息队列:Spring Boot 3.5 中异步架构的演进与选择
spring boot·后端·架构
一只叫煤球的猫7 小时前
MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
后端·sql·mysql
写bug写bug8 小时前
如何正确地对接口进行防御式编程
java·后端·代码规范
MoFe18 小时前
【.net core】【watercloud】树形组件combotree导入及调用
.netcore
MoFe18 小时前
【.net core】.KMZ文件解压为.KML文件并解析为GEOJSON坐标数据集。附KML处理多线(LineString)闭环问题
.netcore