TLDR

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.

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.

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 but this is not the case. The first call to the service will result in a Console.WriteLine(‘Dictionary is empty’), thesuccessive 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!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store