CodexBloom - Programming Q&A Platform

implementing Implementing Dependency Injection in a .NET 6 Web API with Scoped Services

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

I've been working on this all day and I'm working through a tutorial and This might be a silly question, but I'm trying to set up a .NET 6 Web API project where I'm using dependency injection (DI) for my services, but I'm working with some unexpected behavior with scoped services... Specifically, I have two controllers that both depend on a service registered as scoped, and I'm seeing that the same instance of the service is being shared across requests, which leads to incorrect data being returned. Here's a simplified version of my setup: ```csharp public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMyService, MyService>(); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Other configurations... app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } ``` Both controllers look something like this: ```csharp [ApiController] [Route("api/[controller]")] public class FirstController : ControllerBase { private readonly IMyService _myService; public FirstController(IMyService myService) { _myService = myService; } [HttpGet] public IActionResult Get() { return Ok(_myService.GetData()); } } [ApiController] [Route("api/[controller]")] public class SecondController : ControllerBase { private readonly IMyService _myService; public SecondController(IMyService myService) { _myService = myService; } [HttpGet] public IActionResult Get() { return Ok(_myService.GetData()); } } ``` When I hit the endpoints from both controllers in rapid succession, the `GetData()` method appears to return stale data instead of the expected fresh data for each request. I've verified that the `MyService` implementation modifies its internal state in the `GetData()` method, but it seems that the scope is not working as intended. I've also tried to use `AddSingleton` instead of `AddScoped`, and while this does change the behavior, it leads to shared state across all requests, which is definitely not what I want. I've looked through the ASP.NET Core documentation but need to seem to find anything regarding issues with scoped services in API controllers. Any insights on what I might be doing wrong or how to ensure that each request gets a fresh instance of the service would be greatly appreciated. Is there a better approach? My development environment is macOS. Any help would be greatly appreciated! My team is using C# for this service. This is for a web app running on Windows 11.