JohanP
JohanP

Reputation: 5472

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?

Upvotes: 1

Views: 4920

Answers (1)

vsarunov
vsarunov

Reputation: 1547

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.

P.S

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/

Upvotes: 5

Related Questions