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

ASP.NET Core代码生成器使用DI服务组时生成控制器失败

解决方案

1. 执行代码生成命令时显式指定DbContext

代码生成器自动查找DbContext失败时,可在命令中明确指定完整的DbContext类型名称,避免自动解析错误:

dotnet aspnet-codegenerator controller -name DepartmentController -m Department -dc LinkU.Areas.Identity.Data.AppIdentityDbContext --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries

2. 检查DbContext与其他服务的注册顺序

确保AppIdentityDbContext的注册逻辑在自定义扩展方法调用之前执行,因为你的DepartmentManager等服务依赖DbContext,必须先注册DbContext才能完成依赖它的服务注册:

// Program.cs中先注册DbContext
builder.Services.AddDbContext<AppIdentityDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 再调用自定义扩展方法注册其他服务
builder.Services.AddMyDependencyGroup();

3. 修改第三方服务的注册方式

将直接实例化第三方服务的写法改为工厂委托模式,避免代码生成器内存编译时无法解析实例化逻辑:

// 原注册方式
services.AddSingleton(new QRCodeService(new QRCodeGenerator()));

// 修改为工厂委托方式
services.AddSingleton(sp => new QRCodeService(new QRCodeGenerator()));
// 如果QRCodeService有对应的接口,也可以指定接口类型
services.AddSingleton<IQRCodeService>(sp => new QRCodeService(new QRCodeGenerator()));

4. 确认扩展方法命名空间已被引用

检查Program.cs顶部是否添加了扩展方法所在的命名空间引用,确保扩展方法能被正确识别:

using LinkU.Configurations;

5. 清理项目缓存后重新编译

执行以下命令清理项目编译缓存,避免内存编译时加载旧的无效编译结果:

dotnet clean
dotnet build

完成后重新执行代码生成命令。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:23:27