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.
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.
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.
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.
Hope it makes things clearer for you.