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

