CodexBloom - Programming Q&A Platform

ASP.NET Core 6: guide with Dependency Injection for Custom Services in Background Hosted Services

👀 Views: 146 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
asp.net-core dependency-injection background-services csharp

I'm working with an scenario with dependency injection in my ASP.NET Core 6 application when trying to access custom services from a background hosted service. I have a class that inherits from `IHostedService`, and within this class, I attempt to use a custom service that I've registered in the `ConfigureServices` method. Here's how I've set things up: ```csharp public class MyCustomService : IMyCustomService { public string GetData() => "Hello from MyCustomService!"; } public class MyHostedService : IHostedService { private readonly IMyCustomService _myCustomService; public MyHostedService(IMyCustomService myCustomService) { _myCustomService = myCustomService; } public Task StartAsync(CancellationToken cancellationToken) { var data = _myCustomService.GetData(); Console.WriteLine(data); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IMyCustomService, MyCustomService>(); services.AddHostedService<MyHostedService>(); } ``` When I run the application, I see the following behavior in the console: ``` System.InvalidOperationException: Unable to resolve service for type 'Namespace.IMyCustomService' while attempting to activate 'Namespace.MyHostedService'. ``` I've confirmed that `IMyCustomService` is registered as a singleton in the `ConfigureServices` method, and it seems like the `MyHostedService` should be able to access it. I've tried rebuilding the solution and clearing the app caches, but nothing seems to resolve the scenario. Is there something I'm missing regarding the registration of services or the way I'm trying to access them in the background service? Any insights on how to troubleshoot this dependency injection scenario would be greatly appreciated.