CodexBloom - Programming Q&A Platform

How to implement guide with dependency injection for ihostedservice in asp.net core 7 causing nullreferenceexception

👀 Views: 15 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
asp.net-core dependency-injection background-service csharp

I'm working on a personal project and I'm prototyping a solution and I'm working with a `NullReferenceException` when trying to use an `IHostedService` in my ASP.NET Core 7 application. My service is supposed to perform background tasks, but it seems that the dependency injection is not resolving some of the services correctly. Here's the relevant part of my code: ```csharp public class MyBackgroundService : BackgroundService { private readonly IServiceA _serviceA; public MyBackgroundService(IServiceA serviceA) { _serviceA = serviceA ?? throw new ArgumentNullException(nameof(serviceA)); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await _serviceA.DoWorkAsync(); // This line throws NullReferenceException } } ``` In my `Program.cs`, I register the `IHostedService` and the dependencies like this: ```csharp builder.Services.AddScoped<IServiceA, ServiceA>(); builder.Services.AddHostedService<MyBackgroundService>(); ``` When I run the application, I see the following behavior message: `NullReferenceException: Object reference not set to an instance of an object.` This happens when the `MyBackgroundService` tries to call `_serviceA.DoWorkAsync()`. I've verified that `ServiceA` is registered and all its dependencies are correctly set up. I've even tried changing `AddScoped` to `AddSingleton` for `IServiceA` but that didn't help. I've checked the implementation of `ServiceA`, and it seems to be working fine when used in other parts of the application. Does anyone have insights on why this might be happening? Is there something specific about the lifecycle of services in the context of hosted services that I might be missing? I'm on Debian using the latest version of Csharp.