Home » c# » c# – Proper way to create a singleton service in ASP.NET Core – does it have to use the static keyword, or not?-Exceptionshub

c# – Proper way to create a singleton service in ASP.NET Core – does it have to use the static keyword, or not?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

This is really confusing for me. Nothing is stopping us from creating a class with instance fields and
instance methods, versus creating a class with static fields and static methods. Both can be registered as a singleton.

Is there a preferred approach to this problem, and why?

EDIT: I’m not asking about creating a class using the singleton pattern. I’m asking about singleton dependency injecting a class versus injecting the same class but with static defined members/fields/methods/properties.

How to&Answers:

You need to understand the different lifetimes for DI and your needs, in order to choose the proper life span.

  • Transient services are created each time the service is requested (So if in 1 request, a service is used 2 times, it will be created 2 times).
  • Scoped services are created per web request (So if in 1 request, a service is used 2 times, it will be created only once).
  • Singleton is an instance that will last the entire lifetime of the application (All requests will share this one instance).

If in doubt, make it transient.

EDIT

I guess its worth to mention that if you create a services as Transient and they have static properties which you constantly change, then this will affect every other created instance, since static affects the type itself, rather than an instance.

Answer:

I’m asking about […] injecting the same class but with static defined members/fields/methods/properties

That is possible but useless. If a controller requires such a singleton object, then you still have no instance method to call on this object. Your controller have to call static methods on the class.

[…] creating a class with instance fields and instance methods

That is a better way to do because it will allow you to mock the object for unit testing.

If you want concrete example, I’ve coded a class with instance methods to store data about users, which is registered as a singleton object, and used in controller.

Hope it makes things clearer for you.