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

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

相关推荐
橘猫云计算机设计1 小时前
基于Springboot的自习室预约系统的设计与实现(源码+lw+部署文档+讲解),源码可白嫖!
java·spring boot·后端·毕业设计
秋书一叶1 小时前
SpringBoot项目打包为window安装包
java·spring boot·后端
pwzs2 小时前
Spring MVC 执行流程全解析:从请求到响应的七步走
java·后端·spring·spring mvc
小兵张健2 小时前
互联网必备职场知识(4)—— 共情沟通能力
后端·产品经理·运营
AskHarries3 小时前
使用 acme.sh 自动更新 SSL 证书的指南
后端
Chandler243 小时前
Go:反射
开发语言·后端·golang
pwzs3 小时前
深入浅出 MVCC:MySQL 并发背后的多版本世界
数据库·后端·mysql
盒子69103 小时前
go for 闭环问题【踩坑记录】
开发语言·后端·golang
刘大猫264 小时前
Arthas monitor(方法执行监控)
人工智能·后端·监控
追逐时光者5 小时前
MongoDB从入门到实战之MongoDB简介
后端·mongodb