dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.03k stars 4.68k forks source link

IHostedService keeps a huge number of references of disposable transient service. #43819

Closed CamusGao closed 3 years ago

CamusGao commented 3 years ago

ServiceCollectionHostedServiceExtensions.AddHostedService add IHostedService with scoped life time and if my IHostedService using IServiceProvider to get services with transient life time do some work, those transient service cannot be dispose until this scope being disposed while IHostedService will be disposed at the end of this application life time usually.

Dotnet-GitSync-Bot commented 3 years ago

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

davidfowl commented 3 years ago

HostedServices are singletons, you can't change the lifetime because they are only ever resolved once at startup and aren't resolved in a scope.

CamusGao commented 3 years ago

HostedServices are singletons, you can't change the lifetime because they are only ever resolved once at startup and aren't resolved in a scope.

sorry, maybe it's my mistake. I am using dotnet core 3.1. But this List kept a huge number of references of disposable transient services and comsumed memory.

davidfowl commented 3 years ago

Yes, that's by design and unfortunately, it's a bit of a performance trap. Don't resolve transient disposable objects from your IHostedService constructor. If you're looking to do something with a scoped lifetime then you need to explicitly created that scope and resolve services from there.

CamusGao commented 3 years ago

ok, but why do this design.

davidfowl commented 3 years ago

The DI container's is responsible for disposing these objects when the container or scope is disposed. This is true for dependencies of any service that implement IDisposable.

ghost commented 3 years ago

Tagging subscribers to this area: @eerhardt, @maryamariyan See info in area-owners.md if you want to be subscribed.

CamusGao commented 3 years ago

thank you.