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

ASP.NET Core仓储注册导致Add-Migration报错的解决求助

解决建议

问题根源

你的批量注册代码错误地将泛型开放类型(比如Repository<T>)纳入了注册范围,EF Core迁移工具在设计时构建服务提供者时,无法实例化泛型开放类型,进而导致依赖的ApplicationDbContext无法创建。

具体修复步骤

  • 过滤泛型开放类型,修正批量注册逻辑
    在类型筛选的Where条件中添加!item.IsGenericTypeDefinition,排除泛型定义类,只注册非泛型的仓储实现:

    Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(item => item.GetInterfaces()
                .Where(i => i.IsGenericType)
                .Any(i => i.GetGenericTypeDefinition() == typeof(IRepository<>)) 
                && !item.IsAbstract 
                && !item.IsInterface
                && !item.IsGenericTypeDefinition) // 新增:排除泛型开放类型
            .ToList()
            .ForEach(assignedTypes =>
            {
                 var serviceType = assignedTypes.GetInterfaces().First(i => i.GetGenericTypeDefinition() == typeof(IRepository<>));
                 services.AddScoped(serviceType, assignedTypes);
             });
    
  • 单独注册泛型仓储
    对于IRepository<T>和Repository<T>这种泛型仓储对,需要用泛型服务注册方式,直接添加以下代码:

    services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
    
  • 确保DbContext设计时可创建
    如果仍存在ApplicationDbContext创建失败的问题,可检查:

    • 给ApplicationDbContext添加无参构造函数(设计时工具可能需要)
    • 实现IDesignTimeDbContextFactory<ApplicationDbContext>接口,手动提供DbContext的创建逻辑,避免依赖DI容器

内容的提问来源于stack exchange,提问作者dr.Xis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:55:01