CodexBloom - Programming Q&A Platform

Handling Memory Leak When Creating Multiple Instances of a Service in ASP.NET Core 6

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
asp.net-core memory-leak dependency-injection C#

I'm upgrading from an older version and I'm integrating two systems and I'm encountering a memory leak in my ASP.NET Core 6 application when creating multiple instances of a service that accesses a large in-memory data structure. The service is registered as a transient service, and I expected it to be disposed of after use. However, I'm noticing that the application's memory usage keeps growing, especially after handling multiple requests. Here's how I've set up my service: ```csharp public class MyLargeDataService { private readonly List<string> _data; public MyLargeDataService() { _data = LoadData(); // This loads a considerable amount of data into memory } private List<string> LoadData() { // Simulate loading a large dataset return Enumerable.Range(1, 100000).Select(i => "Item " + i).ToList(); } } ``` And I've registered it in `Startup.cs` like this: ```csharp services.AddTransient<MyLargeDataService>(); ``` In my controller, I'm injecting this service: ```csharp public class MyController : ControllerBase { private readonly MyLargeDataService _dataService; public MyController(MyLargeDataService dataService) { _dataService = dataService; } [HttpGet] public IActionResult GetData() { // Use _dataService here return Ok(); } } ``` After several requests, the memory usage keeps increasing without going down. I tried using a scoped service instead, but it didn't solve the issue either. I've also checked for any lingering references to the service, yet I'm still facing the memory growth. The application is running in a Docker container, and I've monitored the memory usage through Docker stats. Is there something I might be missing in the service lifetime management, or is there a pattern I should consider when dealing with large in-memory datasets like this? Any insights would be greatly appreciated! I'm open to any suggestions.