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

使用Entity Framework创建MVC带视图控制器后无法路由,出现依赖注入错误

问题解决方法

错误原因

你的UsersController构造函数依赖Utility(继承自DbContext),但ASP.NET Core的依赖注入容器中未注册该服务,导致框架无法解析依赖、创建控制器实例。

解决步骤

在Program.cs中将Utility DbContext注册到服务容器:

  1. 在builder.Services.AddControllersWithViews();之后添加注册代码:
// 注册Utility DbContext到依赖注入容器
builder.Services.AddDbContext<First_Identity_Project.Models.Utility>(options =>
    options.UseSqlServer("server=.;database=firstIdentityDb;user Id = sa;password= Aa123456;Trusted_Connection = true;trustServerCertificate=true;"));

如果希望保留Utility类中OnConfiguring方法的连接字符串配置,也可以简化注册:

builder.Services.AddDbContext<First_Identity_Project.Models.Utility>();

修改后的完整Program.cs代码

using First_Identity_Project.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// 注册Utility DbContext
builder.Services.AddDbContext<Utility>(options =>
    options.UseSqlServer("server=.;database=firstIdentityDb;user Id = sa;password= Aa123456;Trusted_Connection = true;trustServerCertificate=true;"));

var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

额外优化建议

不要将数据库连接字符串硬编码到代码中,建议存储在appsettings.json并通过配置读取:

  1. 在appsettings.json中添加:
"ConnectionStrings": {
  "DefaultConnection": "server=.;database=firstIdentityDb;user Id = sa;password= Aa123456;Trusted_Connection = true;trustServerCertificate=true;"
}
  1. 修改注册代码为:
builder.Services.AddDbContext<Utility>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

内容的提问来源于stack exchange,提问作者mani agah smailzad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:32:35