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

ASP.NET Core MVC中NorthwindContext服务解析失败问题排查

问题分析与解决方案

核心问题

你的Program.cs同时混用了两种服务配置方式,但未实际执行Startup类的服务注册逻辑,导致NorthwindContext根本没被添加到依赖注入容器中,这是引发“无法解析服务”错误的根本原因。此外还有几处配置细节错误需要修正:


具体修正步骤

1. 重构Program.cs(改用.NET 6+原生配置风格,移除冗余Startup类)

直接删除原Startup.cs文件,将Program.cs修改为以下内容,在顶级语句中完成所有服务注册:

using Microsoft.EntityFrameworkCore;
using MVCcumul_01.Models;

var builder = WebApplication.CreateBuilder(args);

// 注册MVC控制器与视图服务
builder.Services.AddControllersWithViews();

// 从appsettings.json读取正确的连接字符串
var connectionString = builder.Configuration.GetConnectionString("MVCcumul_01Context");
// 注册NorthwindContext(使用EF Core推荐的作用域生命周期,无需手动指定)
builder.Services.AddDbContext<NorthwindContext>(options => 
    options.UseSqlServer(connectionString));

// 如需使用DbContextFactory,同步配置正确的连接字符串
builder.Services.AddDbContextFactory<NorthwindContext>(options => 
    options.UseSqlServer(connectionString));

var app = builder.Build();

// 保留原有HTTP管道配置逻辑
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();

2. 修正ApplicationDbContextFactory的连接字符串引用

你的appsettings.json中不存在DefaultConnection,需要改为实际定义的MVCcumul_01Context:

using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace MVCcumul_01.Models
{
    internal class ApplicationDbContextFactory : IDesignTimeDbContextFactory<NorthwindContext>
    {
        public NorthwindContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var builder = new DbContextOptionsBuilder<NorthwindContext>();
            // 替换为正确的连接字符串名称
            var connectionString = configuration.GetConnectionString("MVCcumul_01Context");

            builder.UseSqlServer(connectionString);

            return new NorthwindContext(builder.Options);
        }
    }
}

3. 移除错误的单例配置

EF Core的DbContext设计为作用域生命周期(每个请求实例化一次),单例模式会引发线程安全问题与数据不一致,因此不要手动指定ServiceLifetime.Singleton,使用AddDbContext的默认配置即可。

4. 验证控制器注入逻辑

确认OrdersController的构造函数正确注入NorthwindContext:

public class OrdersController : Controller
{
    private readonly NorthwindContext _context;

    public OrdersController(NorthwindContext context)
    {
        _context = context;
    }

    // 其他业务方法...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:35:11