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

ASP.NET Core中无法解析StudentDbContext服务的问题求助

解决ASP.NET Core中StudentDbContext无法注入的问题

你遇到的错误信息:

System.InvalidOperationException: Unable to resolve service for type 'webb.StudentDbContext' while attempting to activate 'webb.Controllers.StudentController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method3(Closure , IServiceProvider , Object[] )

以下是具体的修复步骤:


1. 修复Program.cs的服务注册顺序

ASP.NET Core要求所有服务必须在builder.Build()之前注册,你当前把DbContext的注册代码写在了构建应用实例之后,导致服务容器无法识别该依赖。

修改后的Program.cs:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using webb;

var builder = WebApplication.CreateBuilder(args);

// 先注册所有服务
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 注册DbContext(必须放在builder.Build()之前)
builder.Services.AddDbContext<StudentDbContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnStr")));

// 再构建应用实例
var app = builder.Build();

// 后续管道配置不变
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

2. 修正连接字符串名称不匹配

你的appsettings.json中连接字符串的键是StudentConnStr,但之前代码里用了StudentDbContext读取,导致无法获取正确的连接字符串,已在上面的代码中修正。

3. 修复StudentController的字段赋值错误

构造函数中没有正确赋值私有字段,导致即使注入成功,调用时也会出现空引用异常:

修改后的StudentController:

[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
    private readonly StudentDbContext _studentDbContext;

    public StudentController(StudentDbContext studentDbContext)
    {
        _studentDbContext = studentDbContext;
    }

    [HttpGet]
    public IEnumerable<Student> Get()
    {
        return _studentDbContext.Student;
    }
}

4. 优化StudentDbContext构造函数(推荐)

将非泛型的DbContextOptions改为泛型版本,让DI系统更精准地注入配置:

修改后的StudentDbContext:

public class StudentDbContext : DbContext
{
    public DbSet<Student> Student { get; set; }

    public StudentDbContext()
    {
    }

    // 使用泛型DbContextOptions
    public StudentDbContext(DbContextOptions<StudentDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>().HasKey(e => e.id);
    }

    // 可以注释掉OnConfiguring,推荐通过DI配置连接字符串
    // protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    // {
    //     optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=sms;Integrated Security=True; TrustServerCertificate = True");
    // }
}

5. 修正Student模型字段类型错误(重要)

Student模型中的stname字段是int类型,不符合姓名的存储需求,会导致数据库操作异常,需改为string:

修改后的Student模型:

namespace webb.Model
{
    public class Student
    {
        public int id { get; set; }
        public string stname { get; set; }

        // 如果course是课程名称,建议也改为string;如果是课程ID则保留int
        public int course { get; set; }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:40:38