简体   繁体   中英

Dependency injection Singleton into Transient

If I have a service that gets injected as Transient but it has a dependency on IMemoryCache , which gets injected as as a Singleton into the constructor, is this going to cause a memory leak? It seems like the transient service will never be GCd because of this reference to IMemoryCache . Is this the case?

It does not matter that you inject a singleton into a transient, you will get a new instance of the transient service each time but it will inject the same singleton each time to it. If you do not hold any reference to the transient service it will be garbed collected.

You can read about how singleton, transient and scoped work in this question: AddTransient, AddScoped and AddSingleton Services Differences?

UPDATE

Your singleton service will never be garbed collected since the first injection it will exist while your application is running. The resolver will always have a reference to exactly that singleton service. However, the reference to the transient service will not be there thus it will be garbed collected even if it holds reference to the singleton, the garbed collection of the singleton does not depend on the life scope of the transient service.

PS

If you want to monitor memory leaks read up on this one: https://devblogs.microsoft.com/devops/diagnosing-memory-issues-with-the-new-memory-usage-tool-in-visual-studio/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM