CodexBloom - Programming Q&A Platform

Trouble with Dependency Injection for Scoped Services in ASP.NET Core 6 - ServiceProvider missing

👀 Views: 1835 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-17
asp.net-core dependency-injection web-api csharp

I'm working with an scenario when trying to use a scoped service in my ASP.NET Core 6 application. My service is intended to be injected into a controller, but when I try to access it, I'm getting the following behavior: `InvalidOperationException: Unable to resolve service for type 'MyApp.Services.IMyScopedService' while attempting to activate 'MyApp.Controllers.MyController'.` Here's how I've set up the service in my `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddScoped<IMyScopedService, MyScopedService>(); } ``` And here is my controller: ```csharp public class MyController : ControllerBase { private readonly IMyScopedService _myScopedService; public MyController(IMyScopedService myScopedService) { _myScopedService = myScopedService; } [HttpGet] public IActionResult GetData() { var data = _myScopedService.GetData(); return Ok(data); } } ``` I've also confirmed that `MyScopedService` is implementing `IMyScopedService` correctly. The behavior occurs when I try to run the application and hit the endpoint that utilizes `MyController`. I've tried the following troubleshooting steps: - Ensured that `IMyScopedService` and `MyScopedService` are in the same assembly as the controller. - Double-checked that my startup configuration is being hit and that there are no multiple registrations of `IMyScopedService`. - Added logging to see if the service is being registered correctly, but the logs do not show any issues. Could this be related to how the application is set up, specifically around the lifetime of services? Any help would be greatly appreciated!