.NET Core Transient Scope issues

Home / .NET Core Transient Scope issues

Over the weekend, I was playing around with the service scheduler project that I previously blogged about and discovered memory leaking like crazy. This project happened to also use an Entity Framework Core logger implementation.


I stumbled on this issue on github regarding Dotnet Core’s dependency injection:

https://github.com/aspnet/DependencyInjection/issues/456

And it just so happens that I’m injecting the logger’s via Transient scoping options:

// Logging context must be transient..
services.AddDbContext<AppLogContext>(options =>
{
	options.UseSqlServer(loggingConnStr);
	options.UseLoggerFactory(null);
}, ServiceLifetime.Transient);

For the logger provider, I’m passing in a Func to retrieve a repository:

Func<IRepository<AppLogModel>> appLogRepoFactory = () =>
{
	// Create a repository
	return serviceProvider.GetRequiredService<IRepository<AppLogModel>>();
};

Using the logger provider, when an ILogger is needed, the func is executed and retrieves a repository. I could see, while running in debug mode with the Visual Studio debugger attached, memory usage would reach about 1.5GB, and then an out of memory exception would be thrown.

One of the suggestions in the github post was to create a scope for transient objects that aren’t naturally scoped. IE – this applies to pretty much any objects instantiated from the primary composition root that are transient, it would seem. Interestingly, creating a scope for each IRepostiroy, and subsequently its associated DbContext, appears to fix the memory leak.

Func<IRepository<AppLogModel>> appLogRepoFactory = () =>
{
	// Create a scoped repository
	var scope = serviceProvider.CreateScope();
	return scope.ServiceProvider.GetRequiredService<IRepository<AppLogModel>>();
};

After letting the scheduler run for three days with a scheduler task executing every second that loads data via a scoped (HttpContext) IRepository and logging via the application logger, memory no longer appeared to be leaking. I can’t say it’s perfect without during any more analysis than looking at memory usage in Windows’ task manager, but the memory usage does seem stable rather than constantly climbing.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.