.netconsole-applicationautofac

Autofac Resolve is extremely slow in .NET Generic Host HostApplicationBuilder


We have been using Autofac since .net framework 4.8 and its performance has been looking fine. However when we are trying to use exactly the same code into Console Application which is based on .net generic host HostApplicationBuilder (https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host?tabs=appbuilder), it is extremely slow in resolving a pretty heavy component from Autofac scope which took me about 5 seconds. The same code in .net framework 4.8 before was only 0.1 second.

This component is including the EF dbContext creation as well, but I don't think that is an issue because it was working fine in previous .net version.

Sample code where it is trying to resolve the component via Autofac ContainerBuilder is as below:

using(var scope = _container.BeginLifetimeScope())
{
    var component = scope.Resolve<MyComponent>();
}

Has anyone seen similar issue like this?

Thank you very much for any help.

Updated 02/12/2024:

Sorry this question was misleading, actually the bottle neck was at DB connection open, in previous application we keep it once it is already opened and the app is running permanently, whereas in the new application which is a .net generic host HostApplicationBuilder when it is finished the job it is stopped and in sequence it will close the DB connection as well.

DB connection is open when resolving the component that's why I thought because of Autofac. I might have to think on other design solution instead of .net generic host.

Thanks everyone.


Solution

  • Clearly there's not enough information here to help you or do any real troubleshooting. For example, we can't tell what changed or how when you converted the app. It's obviously not literally exactly the same code because you moved from .NET 4.8 to generic hosting in .NET Core, so stuff did change. We can't see what you registered or how you registered it. That's why every question should have a minimal reproduction.

    But, if it was me, stuff I'd look at:

    The perf problem isn't going to be Autofac, it's going to be with what you have registered and how fast Autofac can find the right types for the dependency chain. The constructor of each object in the chain is a cost. It's up to you to use the tools available to analyze where the time is going.