LightInject.Microsoft.DependencyInjection
LightInject.Microsoft.DependencyInjection copied to clipboard
Memory leak in unit tests
Hi,
We use LightInject for many years in multiple big solutions in our company. A few weeks ago we noticed failing CI builds in Azure due to an out-of-memory exception on the build server (6GB RAM). When debugging our tests locally, we also noticed a lineair increase in memory when executing our (2000 a 3000) unit tests.
After searching for a while, we noticed the problem is possibly due to the fact we create a ServiceProvider manually. This is needed for resolving the MediatR class:
private void ConfigureContainer()
{
ContainerManager.Container.Register<IMediator, Mediator>();
//Needed by MediatR (Not needed in AspNetCore projects since that uses the Host.UseLightInject())
if (!ContainerManager.Container.AvailableServices.Any(sr => sr.ServiceType == typeof(IServiceProvider)))
((ServiceContainer)ContainerManager.Container).CreateServiceProvider(new ServiceCollection());
}
I created a fork of your repo and added a separate unit test project with one test illustrating the memory leak: https://github.com/ArnaudB88/LightInject.Microsoft.DependencyInjection/pull/1
I hope you can help us in finding a solution/bugfix.
Thanks! Arnaud
Did this occur after upgrading ?
@seesharper This did occur after we needed to add the ServiceProvider manually for Mediatr. So changing
- the Mediatr nuget version to v11.1.0
- and setting the
CreateServiceProvider()line in comment in theConfigureContainer()method - and add the registration
ContainerManager.Container.Register<ServiceFactory>(factory => factory.GetInstance);in theConfigureContainer()method
should prevent the memory leak.
@seesharper any idea how we can add a ServiceProvider for unit tests but don't have the memory leak issue?
@seesharper as you can see in my latest commit in the PR, it seems that the solution is passing the container options with Microsoft settings:
ContainerOptions.Default.Clone().WithMicrosoftSettings()
Maybe it's an idea to make that de default behavior of LightInject, or to strongly advise using those settings for optimal memory usage. Another option is to investigate why memory is leaking without those settings.