Static members do not get garbage collected through Depedency Injection

Sami C.
1 min readSep 16, 2021

--

TLDR

Static members do not get garbage collected, even if the AddScoped<MyService> lifetime is used. This means that the static variable will keep the same value for every HTTP request made to the service.

My colleague had a question about a static variable maintaining state when a new HTTP call accessed the service. .NET Core has built in Dependency injection.

For information on using dependency injection in applications other than web apps, see Dependency injection in .NET.

This is how our service was registered in the startup.cs:

services.AddScoped<MyService>();

Notice that we’ve used the scoped. When we take a look at the definition of a scoped service.

In apps that process requests, scoped services are disposed at the end of the request.

Take a look at the following code

Since we’ve used a scoped service, our dictionary should always be empty when a new request gets made to loadData(), but this is not the case. The first call to the service will result in a Console.WriteLine(‘Dictionary is empty’), the successive calls will result in dictionary is full. The reason for this behavior is the ‘static’ keyword. Static variables will never get garbage collected as long as the class exists. Therefor, the static keyword will override the Scoped service lifetime defined in our startup.

Enjoy!

--

--