代码之家  ›  专栏  ›  技术社区  ›  Yuri Mckoy

未处理的异常。系统。无效操作异常

  •  0
  • Yuri Mckoy  · 技术社区  · 4 月前

    我正在做一个教程,我一直得到这个错误:

    未处理的异常。系统。InvalidOperationException:找不到所需的服务。请通过调用“IServiceCollection”添加所有必需的服务。在应用程序启动代码中对“ConfigureServices(…)”的调用中添加控制器。

    在微软。AspNetCore。建设者。控制器端点路由构建器扩展。EnsureControllerServices(IEndpointRouteBuilder端点)
    在微软。AspNetCore。建设者。控制器端点路由构建器扩展。地图控制器(IEndpointRouteBuilder端点)
    在节目中$C:\Users\Yuri\web projects\restore\api\Program.cs中的(String[]args):第16行

    我相信它要求我在program.cs文件中添加一些东西,但我不确定是什么。

    program.cs :

    using API.Data;
    using Microsoft.EntityFrameworkCore;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
    builder.Services.AddOpenApi();
    builder.Services.AddDbContext<StoreContext>(opt => 
    {
        opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
    });
    
    var app = builder.Build();
    
    app.MapControllers();
    
    Dbinitializer.InitDb(app);
    
    app.Run();
    

    起初我以为 Dbinitializer.InitDb(app); 这就是问题所在,所以我把它注释掉了,但错误并没有消失。

    1 回复  |  直到 4 月前
        1
  •  1
  •   Guru Stron    4 月前

    错误消息可以说是不言自明的:

    请通过调用“IServiceCollection”添加所有必需的服务。在应用程序启动代码中对“ConfigureServices(…)”的调用中添加控制器。

    您正在拨打电话 app.MapControllers(); 为了公开在控制器中定义的端点,这需要注册一些内部服务(在以下情况下不需要) Minimal APIs ).

    因此,在代码中添加以下调用:

    builder.Services.AddControllers();