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?

- 5,252
- 2
- 24
- 34
1 Answers
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/

- 1,433
- 14
- 26
-
The transient service will have a reference to the singleton service, how can it then be garbage collected? – JohanP May 24 '19 at 06:24
-
1That makes sense. There is no reference to the transient anymore so it gets cleaned up, it doesn't matter whether it has references that are still alive. – JohanP May 24 '19 at 06:33