ASP.NET Core 2.1 - Stack overflow exception related to dependency injection

2

I'm getting a stack overflow exception after I load 4 or 5 times a simple controller action. The web app is running on Azure and I was able to dump the exception information and the problem seems to be related to Dependency Injection.

    internal object GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
    {
        if (_disposed)
        {
            ThrowHelper.ThrowObjectDisposedException(); --> this is executed
        }

        var realizedService = RealizedServices.GetOrAdd(serviceType, _createServiceAccessor);
        _callback?.OnResolve(serviceType, serviceProviderEngineScope);
        return realizedService.Invoke(serviceProviderEngineScope);
    }

Running the web app in my computer has no issues, it only fails in PROD.

This is how I captured the exception in Azure: https://blogs.msdn.microsoft.com/benjaminperkins/2017/06/28/capture-a-stackoverflowexception-and-make-a-dump-0xc00000fd/

I opened the dump in Visual Studio and I could identify the code line where it failed (described above) but I still don't know how to fix it. All my dependencies are resolved with 'scope' lifetime.

Any help is appreciated.

.net-core
dependency-injection
stack-overflow
asked on Stack Overflow Jan 6, 2020 by Francisco Goldenstein • edited Jan 6, 2020 by Francisco Goldenstein

1 Answer

2

I finally fixed it! I had a class that had like 20 dependencies and each dependency had more dependencies, maybe 4 or 5 level. There were no circular dependencies because this was working fine in my development environment. After I did a refactoring and reduced the dependencies, it worked out fine.

Because it was working fine in my development environment but not in Azure App Service, I assume there's some limitation on the dependency instances or levels you can define when the app is hosted in Azure.

This was my methodology to fix it:

  1. Find the simplest case that fails.

  2. Comment out all the depedencies and try again. It worked, ok, it's about dependencies.

  3. Dump the stack overflow exception in production as this error didn't occur in the dev environment.

  4. Confirm it's a dependency injection issue and examine .NET Core source code.

  5. Reduce dependency instances and levels.

  6. Deploy. If it doesn't work, go to (5). If it works, you are happy again :)

A few weeks later I had more issues and I finally decided to migrate to AutoFac. It's been working perfectly since then. AutoFac is much more mature than the built-in dependency injection.

answered on Stack Overflow Jan 7, 2020 by Francisco Goldenstein • edited Dec 1, 2020 by Francisco Goldenstein

User contributions licensed under CC BY-SA 3.0