runtime: StackOverflowException when using Microsoft.Extensions.DependencyInjection
Update: It also occurs in a ASP.NET Core API project (see below)
Describe the bug
I am currently working on a ASP.NET MVC5 project that targets .NET472. A lot of business logic needs to be shared with a ASP.NET Core 6 project, so we’re using multi-target to do that. Because of the same reason, we have switched our dependency injection from Unity to Microsoft.Extensions.DependencyInjection, so both application (old MVC5 + new ASP.NET Core6 API) can use the same way of registering services.
However, now we have switched to Microsoft.Extensions.DependencyInjection v5.0.2 (can’t use 6.0.0 because of an incompatible 3rd party package), we’re hitting the same StackOverflowException as described here https://github.com/dotnet/aspnetcore/issues/2737. Every other request gives us that exception.
The workaround described here no longer works, because the options object has been changed, but the idea behind it still works: switch from dynamic provider engine to the runtime provider engine.
A similar workaround for MS DI version 5.0.2 looks like this:
var serviceProviderType = typeof(ServiceProvider);
var serviceProviderEngineInterfaceType = serviceProviderType.Assembly.GetType("Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngine");
var serviceProviderConstructor = serviceProviderType.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new[]
{
typeof(IServiceCollection),
serviceProviderEngineInterfaceType,
typeof(ServiceProviderOptions)
},
null);
var runtimeEngineType = serviceProviderType.Assembly.GetType("Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeServiceProviderEngine");
var runtimeEngineConstructor = runtimeEngineType.GetConstructor(new[] { typeof(IServiceCollection) });
var engine = runtimeEngineConstructor.Invoke(new[] { services });
var serviceProvider = serviceProviderConstructor.Invoke(new[] { services, engine, new ServiceProviderOptions() });
return (IServiceProvider)serviceProvider;
instead of simply calling:
services.BuildServiceWorker();
I have seen that the code for MS DI 6 has changed considerably, so the workaround would also need to be fixed in the future (unless we get everything on .NET 6 in the meantime).
However, my question is: why is the dynamic engine causing this issue and would it be possible to add a setting to the ServiceProviderOptions that lets us select the engine mode?
Further technical details
- ASP.NET version: 5
- ASP.NET Core version: 6
- The IDE (VS / VS Code/ VS4Mac) you’re running on, and its version: VS2019 / VS2022 / Rider
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 21 (9 by maintainers)
Oops, wrong repository. Can someone move this issue to dotnet/runtime please 😬?
@eerhardt We are unable to reproduce it in .NET 7, so this can be closed.