CodexBloom - Programming Q&A Platform

Unexpected Behavior with Dependency Injection of Scoped Services in ASP.NET Core 7

πŸ‘€ Views: 50 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
asp.net-core dependency-injection csharp C#

I've searched everywhere and can't find a clear answer. I'm encountering a perplexing issue with the dependency injection of scoped services in my ASP.NET Core 7 application. I have a service that is registered as scoped and I'm trying to inject it into a singleton service, but I get an 'InvalidOperationException' stating that 'Cannot consume scoped service 'MyScopedService' from singleton 'MySingletonService'.' I thought it was valid to inject scoped services into singleton services as long as they are resolved correctly, but it seems I am mistaken. To illustrate the issue, here’s a simplified version of my code: ```csharp public class MyScopedService { public string GetData() => "Hello from Scoped Service!"; } public class MySingletonService { private readonly MyScopedService _myScopedService; public MySingletonService(MyScopedService myScopedService) { _myScopedService = myScopedService; // This causes the exception } public string GetGreeting() => _myScopedService.GetData(); } public void ConfigureServices(IServiceCollection services) { services.AddScoped<MyScopedService>(); services.AddSingleton<MySingletonService>(); } ``` I’ve tried using a factory pattern to resolve the scoped service within a method instead of directly through the constructor, but that felt more like a workaround than a solution. My current workaround looks like this: ```csharp public class MySingletonService { private readonly IServiceProvider _serviceProvider; public MySingletonService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public string GetGreeting() { using (var scope = _serviceProvider.CreateScope()) { var myScopedService = scope.ServiceProvider.GetRequiredService<MyScopedService>(); return myScopedService.GetData(); } } } ``` While this approach works, I'm not sure if it's the best practice. Is there a way to properly inject scoped services into singleton services in ASP.NET Core without resorting to creating a scope manually? What are the recommended patterns for such scenarios? Any ideas what could be causing this? I'm working with C# in a Docker container on Ubuntu 22.04. Is this even possible?