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

Blazor Server应用报错:未注册CompentencyProject5.Data.CustomerServices服务

解决Blazor Server中CustomerServices未注册的错误

问题描述

开发Blazor Server应用时,访问“Fetchdata”页面出现错误:

Error: System.InvalidOperationException: No service for type 'CompentencyProject5.Data.CustomerServices' has been registered.

错误发生在代码行customers = await @Service.getCustomersAsync(UserIdentityName);处。

解决步骤

1. 将CustomerServices注册到依赖注入容器

在项目的Program.cs(.NET 6及以上版本)或者Startup.cs(.NET 5及更早版本)中,添加服务注册代码:

Program.cs示例(.NET 6+):

var builder = WebApplication.CreateBuilder(args);

// 注册DbContext(需提前配置好连接字符串)
builder.Services.AddDbContext<CompentencyProject5DataBaseContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("YourConnectionStringName")));

// 注册CustomerServices,推荐使用Scoped生命周期
builder.Services.AddScoped<CustomerServices>();

// 其他服务注册代码...

var app = builder.Build();

// 中间件配置代码...

Startup.cs示例(.NET 5及更早):

public void ConfigureServices(IServiceCollection services)
{
    // 注册DbContext
    services.AddDbContext<CompentencyProject5DataBaseContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("YourConnectionStringName")));

    // 注册CustomerServices
    services.AddScoped<CustomerServices>();

    // 其他服务注册代码...
}

2. 在组件中正确注入CustomerServices

修改Fetchdata组件的代码,添加[Inject]属性注入服务,并移除无效的@Service语法:

@code
{
    [CascadingParameter]
    private Task<AuthenticationState>? authenticationStateTask{ get; set; }
    
    // 注入CustomerServices实例
    [Inject]
    private CustomerServices? Service { get; set; }
    
    List<CompentencyProject5Users> customers = new List<CompentencyProject5Users>();
    private string UserIdentityName = "";

    protected override async Task OnInitializedAsync()
    {
        if (authenticationStateTask != null)
        {
            var user = (await authenticationStateTask).User;

            if (user.Identity != null)
            {
                UserIdentityName = user.Identity.Name ?? "";
            }
        }

        // 添加空值检查,避免运行时空引用异常
        if (Service != null)
        {
            customers = await Service.getCustomersAsync(UserIdentityName);
        }
    }
}

关键说明

  • Blazor依赖注入系统要求所有需注入的服务必须提前注册到容器,否则会抛出未注册异常。
  • AddScoped表示每个用户会话创建一个服务实例,适合数据库操作类服务的生命周期需求。
  • 添加空值检查是为了适配Nullable上下文规则,避免编译警告和运行时错误。

内容的提问来源于stack exchange,提问作者Zar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:50:26