CodexBloom - Programming Q&A Platform

Struggling with Dependency Injection and Scoped Services in ASP.NET Core 6 - 'Cannot resolve scoped service' error

👀 Views: 89 💬 Answers: 1 📅 Created: 2025-09-06
aspnet-core dependency-injection scoped-services C#

I recently switched to I'm getting frustrated with I'm getting frustrated with I can't seem to get I'm stuck on something that should probably be simple. I'm facing an issue with dependency injection in my ASP.NET Core 6 application, specifically with scoped services. I have a service `MyService` that is registered as scoped, and I try to inject it into a controller that is also scoped. However, when I run the application, I get the error message: `Cannot resolve scoped service 'MyNamespace.MyService' from root provider.` Here's how I've set up my `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddScoped<MyService>(); // Registering MyService as scoped } ``` And my controller looks like this: ```csharp [ApiController] [Route("api/[controller]")] public class MyController : ControllerBase { private readonly MyService _myService; public MyController(MyService myService) { _myService = myService; } } ``` I’ve tried changing the service registration to singleton, but then I run into issues with data consistency because `MyService` relies on per-request data. I also checked if I was resolving the controller from the dependency injection container, and I am, as I’m using dependency injection in the controller constructor as shown. Despite this, I still keep receiving the same error. I've checked the configurations and they seem fine. Can anyone suggest what might be going wrong here or how to resolve this issue? I appreciate any insights! I'm working on a service that needs to handle this. I'd really appreciate any guidance on this. This issue appeared after updating to C# 3.9. What's the best practice here? This is for a CLI tool running on Ubuntu 20.04. I'm open to any suggestions. Hoping someone can shed some light on this. Has anyone else encountered this?