You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WebAssembly注册QuestionService后仍无法注入引发InvalidOperationException的问题求助

Blazor WebAssembly注册QuestionService后仍无法注入引发InvalidOperationException的问题求助

我最近在Blazor WebAssembly项目里开发CRUD功能,结果遇到了一个完全卡壳的问题——不管怎么试,页面里注入QuestionService的时候总是抛出异常,提示找不到对应的注册服务。Github Copilot给的建议都是检查拼写、命名空间这种基础项,但我反复核对过都没问题,现在实在没辙了,想请教各位大佬有没有其他排查方向?

错误信息

InvalidOperationException: Cannot provide a value for property 'QuestionService' on type 'PWAQuestionWASM.Client.Pages.Questions'. There is no registered service of type 'PWAQuestionWASM.Client.Services.QuestionService'.

我的Program.cs代码

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using PWAQuestionWASM.Client.Services;
using System.Net.Http;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddAuthorizationCore();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddAuthenticationStateDeserialization();

// 注册QuestionService
builder.Services.AddScoped<QuestionService>();

await builder.Build().RunAsync();

我的QuestionService.cs代码

using System.Net.Http.Json;
using PWAQuestionWASM.Shared.Models;

namespace PWAQuestionWASM.Client.Services
{
    public class QuestionService
    {
        private readonly HttpClient _http;

        public QuestionService(HttpClient http)
        {
            _http = http;
        }

        public async Task<List<Question>> GetQuestionsAsync() 
            => await _http.GetFromJsonAsync<List<Question>>("api/questions") ?? new();

        public async Task<Question?> GetQuestionAsync(int id) 
            => await _http.GetFromJsonAsync<Question>($"api/questions/{id}");

        public async Task<Question?> CreateQuestionAsync(Question question)
        {
            var response = await _http.PostAsJsonAsync("api/questions", question);
            return await response.Content.ReadFromJsonAsync<Question>();
        }

        public async Task<bool> UpdateQuestionAsync(Question question)
        {
            var response = await _http.PutAsJsonAsync($"api/questions/{question.Id}", question);
            return response.IsSuccessStatusCode;
        }

        public async Task<bool> DeleteQuestionAsync(int id)
        {
            var response = await _http.DeleteAsync($"api/questions/{id}");
            return response.IsSuccessStatusCode;
        }
    }
}

我已经做过的检查

  • 确认QuestionService的命名空间PWAQuestionWASM.Client.Services完全正确,Program.cs里也正确引用了该命名空间
  • 核对了QuestionService的类名、注入时的属性名拼写,没有任何错误
  • 检查了服务注册的顺序,确保在Build().RunAsync()之前完成注册

有没有大佬能告诉我,除了这些基础项,还有什么地方可能出问题?比如Blazor WASM的注入有没有什么特殊的坑我没注意到?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:18:05