I have troubleshooted a memory leak within my application down to an improper use of a transient Idisposable service.
The service is implemented as
public interface IUnitOfWork : IDisposable, IAsyncDisposable
{
}
It is injected as
public static IServiceCollection AddUnitOfWork(this IServiceCollection services)
=> services.AddTransient<IUnitOfWork>(services => new UnitOfWork(services.GetRequiredService<IConfiguration>()));
and it is usually consumed like this
void DoStuff()
{
using var uow = serviceProvider.GetRequiredService<IUnitOfWork>();
}
The thing is, there are way too many consumers that get the service that way, making it almost impossible to refactor the whole codebase.
Microsoft guidance states that a factory pattern should be used instead. Is there any way where I can change the injection part of the code and avoid the memory leak without changing every consumers?
I have tried using multiple ways of injecting the service, they all seem to cause a memory leak.