.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(); }
3. Improve Service Registration (Optional but Recommended)
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
serviceAddressis correctly populated inProgram.cs(check your configuration if using appsettings). - Run the app again—the
NullReferenceExceptionshould be resolved.
内容的提问来源于stack exchange,提问作者Cal
相关产品推荐
相关产品推荐

