Blazor 错误:“没有该类型的注册服务”——其他 StackOverflow 问题无法解决

Joh*_*n D 2 c# progressive-web-apps asp.net-core blazor-webassembly

在我的 .Net CORE 5(导入的支持文件 v5.0.12)Blazor PWA VS-2019 解决方案中,我“拥有”一个工作的“客户”-(数据/应用程序)服务和 Blazor 页面来列出和 CRUD 客户记录(工作原理为预期的)。我为服务器项目和客户端项目创建了类似的“车辆”文件(当然更改了模型字段引用)。

目前还没有编译错误,当我尝试显示“VehicleList”页面时,此错误出现在输出窗口中:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常渲染组件:无法为类型 'MyCore5AppPWA.Client.Pages.VehicleList'上的属性'_vehicleService'提供值。没有类型为'MyCore5AppPWA.Client.Services.IVehicleService'的已注册服务。System.InvalidOperationException:无法为类型'MyCore5AppPWA.Client.Pages.VehicleList'上的属性'_vehicleService'提供值 。 没有类型为'MyCore5AppPWA.Client.Services.IVehicleService'的已注册服务。在 Microsoft.AspNetCore.Components.ComponentFactory.<> c__DisplayClass6_0 .g__Initialize|2(IServiceProvider serviceProvider,IComponent 组件)

请注意上面的“...c__DisplayClass6_0...”符号,这对我来说很好奇(不知道其意义)。我已经阅读了许多与本文主题相关的类似问题/答案,但这些问题/答案并未纠正错误。

以下是 Startup.cs 文件中的片段:

  public void ConfigureServices(IServiceCollection services) {

     _ = services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));

     services.AddScoped<ICustomerRepository, CustomerRepository>();
     services.AddScoped<IVehicleRepository, VehicleRepository>();

     services.AddControllersWithViews();
     services.AddRazorPages();

     services.AddScoped<WeatherForecastService>();

  }
Run Code Online (Sandbox Code Playgroud)

以下是“VehicleList.razor”代码文件中的片段。

//html... declarations.
@layout MainLayout
@page "/vehiclelist"
@using MyCore5AppPWA.Client.Services;
@using MyCore5AppPWA.Shared
//...html omitted...//

@code {

   [Inject] 
   private IVehicleService _vehicleService { get; set; }

   [Inject] 
   private NavigationManager navigationManager { get; set; } ...other code...
Run Code Online (Sandbox Code Playgroud)

我在 SERVER-project/Controllers 子文件夹中还有一个“CustomerController.cs”和一个“VehicleController.cs”。

由于我对 Blazor/Core-5/PWA 相当陌生,因此我得出的结论是,我遗漏了一些有关向 PWA 项目添加新服务的内容。

非常欢迎您提出意见和建议。谢谢约翰

JOS*_*Ftw 7

您正在 VehicleList.razor 文件中注入 IVehicleService。但您似乎没有在 DI 容器中注册此接口的任何实现?

没有类型为“MyCore5AppPWA.Client.Services.IVehicleService”的注册服务

就像是

services.AddScoped<IVehicleService, YourImplementation>();
Run Code Online (Sandbox Code Playgroud)

应该解决它。

请注意,您需要根据您的实现以正确的生命周期(单例、作用域或瞬态)注册它。