![](/img/trans.png)
[英]ASP.NET Core - System.InvalidOperationException: Unable to resolve service for type while attempting to activate
[英]System.InvalidOperationException: Unable to resolve service in ASP.NET Core
我是 ASP.NET Core 的初学者。 我正在创建一个 Web API 服务。 当我从数据库中获取数据时,遇到了问题。 我得到的错误是什么? 我已经成功完成了数据库迁移部分并成功创建了数据库。
System.InvalidOperationException:尝试激活“webb.Controllers.StudentController”时无法解析类型“webb.StudentDbContext”的服务。
在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,类型类型,类型 requiredBy,Boolean isDefaultParameterRequired)
在 lambda_method3(闭包,IServiceProvider,对象[])
StudentController
:
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private StudentDbContext studentDbContext;
public StudentController(StudentDbContext studentDbContext)
{
studentDbContext = studentDbContext;
}
// GET: api/<EmployeeController>
[HttpGet]
public IEnumerable<Student> Get()
{
return studentDbContext.Student;
}
}
Model class:
namespace webb.Model
{
public class Student
{
public int id { get; set; }
public int stname { get; set; }
public int course { get; set; }
}
}
StudentDbContext
:
public class StudentDbContext : DbContext
{
public DbSet<Student> Student { get; set; }
public StudentDbContext()
{
}
public StudentDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasKey(e => e.id);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=sms;Integrated Security=True; TrustServerCertificate = True");
}
}
appsettings.json
:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"StudentConnStr": "Data Source=.;Initial Catalog=sms;Integrated Security=True;"
}
}
我要在哪里设置密钥。
Program.cs
:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using webb;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
builder.Services.AddDbContext<StudentDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("StudentDbContext")));
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
看起来您错过了将StudentDbContext
注入 DI 容器的 DbContext。
将以下内容添加到您的 Program.cs:
builder.Services.AddDbContext<StudentDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnStr")));
请参阅此和第 5 部分,在 ASP.NET Core MVC 应用程序中使用数据库
更新
builder.Services.AddDbContext<StudentDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnStr")));
var app = builder.Build();
builder.Build()
应该在所有AddXXX
函数之后。 换句话说,您需要将其与AddDbContext()
交换
builder.Services.AddDbContext<StudentDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("StudentDbContext")));
var app = builder.Build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.