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

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

相关推荐
短剑重铸之日2 小时前
《7天学会Redis》特别篇: Redis分布式锁
java·redis·分布式·后端·缓存·redission·看门狗机制
小北方城市网2 小时前
SpringBoot 全局异常处理与接口规范实战:打造健壮可维护接口
java·spring boot·redis·后端·python·spring·缓存
hanqunfeng3 小时前
(三十三)Redisson 实战
java·spring boot·后端
小北方城市网3 小时前
SpringBoot 集成 MyBatis-Plus 实战(高效 CRUD 与复杂查询):简化数据库操作
java·数据库·人工智能·spring boot·后端·安全·mybatis
hanqunfeng5 小时前
(四十)SpringBoot 集成 Redis
spring boot·redis·后端
小北方城市网5 小时前
SpringBoot 集成 MinIO 实战(对象存储):实现高效文件管理
java·spring boot·redis·分布式·后端·python·缓存
程序员泠零澪回家种桔子5 小时前
RAG自查询:让AI精准检索的秘密武器
人工智能·后端·算法
曹轲恒6 小时前
SpringBoot配置文件(1)
java·spring boot·后端
小北方城市网6 小时前
SpringBoot 安全认证实战(Spring Security + JWT):打造无状态安全接口体系
数据库·spring boot·后端·安全·spring·mybatis·restful
rannn_1116 小时前
【Javaweb学习|Day7】事务管理、文件上传
后端·学习·javaweb