CodexBloom - Programming Q&A Platform

Unexpected 'InvalidOperationException' While Using Dependency Injection with Scoped Services in ASP.NET Core 6

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
asp.net-core dependency-injection scoped-services C#

I'm stuck on something that should probably be simple... I'm working with an `InvalidOperationException` when trying to resolve a scoped service from a singleton service in my ASP.NET Core 6 application. The exception message states: `want to resolve scoped service 'MyApp.Services.IMyScopedService' from root provider.` I've set up a basic web API application and registered my services like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMyScopedService, MyScopedService>(); services.AddSingleton<IMySingletonService, MySingletonService>(); } ``` The `MySingletonService` tries to inject `IMyScopedService` like this: ```csharp public class MySingletonService : IMySingletonService { private readonly IMyScopedService _myScopedService; public MySingletonService(IMyScopedService myScopedService) { _myScopedService = myScopedService; } } ``` When I try to call an endpoint that uses `MySingletonService`, I get the exception above. To troubleshoot, I have tested the scoped service independently in a controller, and it works without issues. I understand that scoped services are not intended to be accessed from singleton instances, but I'm unsure how to structure my code to avoid this question. One workaround I considered was to pass the `IServiceProvider` to `MySingletonService` and resolve `IMyScopedService` directly when needed, but I'm concerned about potential performance impacts and service lifetimes. Can someone recommend a better approach or best practices to handle this scenario? This is my first time working with C# 3.11. What's the correct way to implement this?