简体   繁体   English

System.InvalidOperationException:无法解析 ASP.NET Core 中的服务

[英]System.InvalidOperationException: Unable to resolve service in ASP.NET Core

I am a beginner in ASP.NET Core.我是 ASP.NET Core 的初学者。 I am creating a Web API service.我正在创建一个 Web API 服务。 While I am fetching the data from the database, I had a problem.当我从数据库中获取数据时,遇到了问题。 What is the error I got?我得到的错误是什么? I have successfully done the database migration part and created the database successfully.我已经成功完成了数据库迁移部分并成功创建了数据库。

System.InvalidOperationException: Unable to resolve service for type 'webb.StudentDbContext' while attempting to activate 'webb.Controllers.StudentController'. System.InvalidOperationException:尝试激活“webb.Controllers.StudentController”时无法解析类型“webb.StudentDbContext”的服务。

at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)在 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,类型类型,类型 requiredBy,Boolean isDefaultParameterRequired)
at lambda_method3(Closure, IServiceProvider, Object[] )在 lambda_method3(闭包,IServiceProvider,对象[])

StudentController : 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: Model class:

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

        public int course { get; set; }
    }
}

StudentDbContext : 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 : appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "StudentConnStr": "Data Source=.;Initial Catalog=sms;Integrated Security=True;"
  }
}

Where I am going to set the key.我要在哪里设置密钥。

Program.cs : 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();

Look like you are missing out inject StudentDbContext which is the DbContext to DI container.看起来您错过了将StudentDbContext注入 DI 容器的 DbContext。

Add below to your Program.cs:将以下内容添加到您的 Program.cs:

builder.Services.AddDbContext<StudentDbContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnStr")));

refer to this and Part 5, work with a database in an ASP.NET Core MVC app请参阅第 5 部分,在 ASP.NET Core MVC 应用程序中使用数据库

Update更新

builder.Services.AddDbContext<StudentDbContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("StudentConnStr")));

var app = builder.Build();

builder.Build() should be after all AddXXX functions. builder.Build()应该在所有AddXXX函数之后。 In other words, you need to swap it with AddDbContext()换句话说,您需要将其与AddDbContext()交换

builder.Services.AddDbContext<StudentDbContext>(options =>
 options.UseSqlServer(builder.Configuration.GetConnectionString("StudentDbContext")));

var app = builder.Build();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET 核心 - System.InvalidOperationException:尝试激活时无法解析服务类型 - ASP.NET Core - System.InvalidOperationException: Unable to resolve service for type while attempting to activate System.InvalidOperationException:无法在数据迁移中的asp.net mvc 6上解析EF7中的项目“ ef” - System.InvalidOperationException: Unable to resolve project 'ef' in EF7 at asp.net mvc 6 in data migration ASP.NET 核心 API System.InvalidOperationException 在本地化 - ASP.NET Core API System.InvalidOperationException in localization ASP.Net 错误 System.InvalidOperationException - ASP.Net error System.InvalidOperationException System.InvalidOperationException:尝试激活时无法解析服务类型 - System.InvalidOperationException: Unable to resolve service for type while attempting to activate System.InvalidOperationException:无法解析类型的服务 - 依赖注入 - System.InvalidOperationException: Unable to resolve service for type - Dependency Injection ASP.NET Core InvalidOperationException:尝试激活UserStore时无法解析DbContext类型的服务 - ASP.NET Core InvalidOperationException: Unable to resolve service for type DbContext while attempting to activate UserStore ASP.NET Core 6 Web API 的集成测试抛出 System.InvalidOperationException - Integration test for ASP.NET Core 6 web API throws System.InvalidOperationException Asp.net 核心System.InvalidOperationException: 无法追踪实体类型x的实例 - Asp.net core System.InvalidOperationException: The instance of entity type x cannot be tracked System.InvalidOperationException:idp 声明丢失身份服务器 4.1.1 Asp.net 核心 3 - System.InvalidOperationException: idp claim is missing Identity server 4.1.1 Asp.net core 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM