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

.NET Core依赖注入构造传参后Razor组件空引用异常求助

Solution to NullReferenceException in Blazor Service Injection

Root Causes

  • The [Inject] property is private, so Blazor's DI system can't set its value via reflection.
  • You're calling myService.DoWork() in the component constructor, which runs before Blazor injects dependencies into the component.

Step-by-Step Fixes

1. Correct the Injected Property Accessibility

Blazor requires public properties for dependency injection. Update your component code to make the property public:

[Inject]
public MyService MyService { get; set; }

(PascalCase is standard for public properties, but the critical change is adding the public modifier.)

2. Move Service Usage to a Lifecycle Method

Use Blazor's OnInitialized or OnInitializedAsync methods—these run after dependencies are injected, making it safe to call service methods:

public WeatherForecast()
{
    // Avoid service calls here
}

protected override void OnInitialized()
{
    MyService.DoWork(); // Service is now properly injected
}

If DoWork is asynchronous, use the async lifecycle method:

protected override async Task OnInitializedAsync()
{
    await MyService.DoWorkAsync();
}

Instead of directly instantiating MyService, use a factory function to resolve dependencies (like configuration) through the service provider. This is more flexible if your service needs other dependencies later:

// Retrieve service address from configuration (e.g., appsettings.json)
var serviceAddress = builder.Configuration["ServiceAddress"];

// Register the service with a factory
builder.Services.AddSingleton<MyService>(sp => 
{
    // Resolve other required services here using sp.GetRequiredService<T>() if needed
    return new MyService(serviceAddress);
});

Verification

After applying these changes:

  • Confirm serviceAddress is correctly populated in Program.cs (check your configuration if using appsettings).
  • Run the app again—the NullReferenceException should be resolved.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:30:42