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

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

相关推荐
山岚的运维笔记13 分钟前
SQL Server笔记 -- 第72章:隔离级别与锁定
数据库·笔记·后端·sql·microsoft·sqlserver
想用offer打牌2 小时前
一站式了解接口防刷(限流)的基本操作
java·后端·架构
何中应2 小时前
RabbitMQ安装及简单使用
分布式·后端·消息队列
何中应2 小时前
使用Python统计小说语言描写的字数
后端·python
何中应2 小时前
SpringAMQP消息转化器
分布式·后端·消息队列
等....8 小时前
MobaXterm操作虚拟机
后端
笨蛋不要掉眼泪9 小时前
Sentinel 流控规则详解:三种模式与三种效果实战指南
java·jvm·数据库·后端·sentinel
健康平安的活着9 小时前
AI之Toolcalling的使用案例(langchain4j+springboot)
人工智能·spring boot·后端
PythonFun9 小时前
HAProxy端口转发入门:从“搬砖工”到“智能交通警察”
服务器·后端·网络安全