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());

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

相关推荐
派大鑫wink1 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势
java·spring boot·后端
程序员爱钓鱼1 小时前
Node.js 编程实战:文件读写操作
前端·后端·node.js
xUxIAOrUIII1 小时前
【Spring Boot】控制器Controller方法
java·spring boot·后端
Dolphin_Home1 小时前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)
java·spring boot·后端·spring cloud·database·广度优先·图搜索算法
zfj3211 小时前
go为什么设计成源码依赖,而不是二进制依赖
开发语言·后端·golang
weixin_462446232 小时前
使用 Go 实现 SSE 流式推送 + 打字机效果(模拟 Coze Chat)
开发语言·后端·golang
JIngJaneIL2 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
小信啊啊2 小时前
Go语言切片slice
开发语言·后端·golang
Victor3564 小时前
Netty(20)如何实现基于Netty的WebSocket服务器?
后端
缘不易4 小时前
Springboot 整合JustAuth实现gitee授权登录
spring boot·后端·gitee