CodexBloom - Programming Q&A Platform

advanced patterns When Using IAsyncDisposable in ASP.NET Core 6 with Scoped Services

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
aspnet-core async-await idisposable C#

This might be a silly question, but I'm updating my dependencies and I'm sure I'm missing something obvious here, but I'm running into an scenario where my scoped services that implement `IAsyncDisposable` are not being disposed of as expected when my ASP.NET Core 6 application ends its request..... I have a service that looks like this: ```csharp public class MyService : IAsyncDisposable { public async ValueTask DisposeAsync() { // Simulate async cleanup await Task.Delay(100); Console.WriteLine("MyService disposed"); } } ``` I register this service in `Startup.cs` like so: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddScoped<MyService>(); } ``` In my controller, I'm using dependency injection as follows: ```csharp public class MyController : ControllerBase { private readonly MyService _myService; public MyController(MyService myService) { _myService = myService; } // Action methods... } ``` However, I noticed that the `DisposeAsync` method is not being called at the end of the request lifecycle. I've tried adding a logging statement at the beginning of the `DisposeAsync` method to verify if it's being executed, but it never shows up in the logs. I double-checked my `Program.cs` to ensure that I'm using `Host.CreateDefaultBuilder()` which should handle the dependency injection lifecycle correctly. I also tried calling `DisposeAsync` manually in my action method like so: ```csharp public async Task<IActionResult> SomeAction() { // Use the service await _myService.SomeMethod(); await _myService.DisposeAsync(); // This works but feels wrong return Ok(); } ``` Using this manual disposal works, but it feels like I'm breaking the intended lifecycle management. Is there something I'm missing regarding how ASP.NET Core manages the disposal of scoped services? Shouldn't `DisposeAsync` be handled automatically when the request completes? Any insights would be greatly appreciated, as I'm exploring on this scenario. Am I missing something obvious? This is part of a larger application I'm building. Is there a better approach? I recently upgraded to C# 3.11. Am I missing something obvious? Is there a better approach? The project is a web app built with C#. Hoping someone can shed some light on this.