You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过依赖注入批量注册所有IRepository接口?

一次性注册.NET中所有仓储模式的依赖注入

当仓储数量较多时,手动逐个注册会导致代码冗余,你可以通过反射扫描程序集的方式批量完成注册,结合你所有仓储实现都继承自GenericRepository的特点,具体实现如下:

1. 编写扩展方法实现批量注册

创建一个静态扩展类,封装批量注册的逻辑:

using System.Reflection;
using Microsoft.Extensions.DependencyInjection;

public static class RepositoryRegistrationExtensions
{
    public static IServiceCollection AddAllRepositories(this IServiceCollection services)
    {
        // 获取仓储所在的程序集(如果仓储在单独类库,替换为typeof(GenericRepository).Assembly)
        var targetAssembly = Assembly.GetExecutingAssembly();

        // 筛选所有继承自GenericRepository的非抽象、非接口的具体仓储类
        var repositoryImplementations = targetAssembly.GetTypes()
            .Where(type => !type.IsAbstract 
                         && !type.IsInterface 
                         && type.IsSubclassOf(typeof(GenericRepository)));

        foreach (var implType in repositoryImplementations)
        {
            // 匹配对应的I开头的仓储接口(例如CustomerRepository对应ICustomerRepository)
            var interfaceType = implType.GetInterface($"I{implType.Name}");
            if (interfaceType != null)
            {
                // 按Scoped生命周期注册(可根据需求改为AddTransient/AddSingleton)
                services.AddScoped(interfaceType, implType);
            }
        }

        return services;
    }
}

2. 在Program.cs中调用扩展方法

只需一行代码即可完成所有仓储的注册:

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddControllersWithViews();
    // 批量注册所有仓储
    builder.Services.AddAllRepositories();

    var app = builder.Build();
    // ... 后续中间件配置
}

注意事项

  • 程序集匹配:如果仓储类和接口不在启动项目程序集,将Assembly.GetExecutingAssembly()替换为仓储所在程序集的引用,比如typeof(CustomerRepository).Assembly
  • 命名规范:确保仓储接口严格遵循I{仓储实现类名}的命名规则,否则无法自动匹配接口
  • 生命周期调整:根据业务需求,可将AddScoped替换为AddTransient(每次请求创建新实例)或AddSingleton(全局单例)

内容的提问来源于stack exchange,提问作者tooMuchLagWillKillYou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:12:18