Why I should use
AddScoped() for my repositories or services? Why not
I know about differences between them, but dont understand why I shouldn’t use singleton instances to avoid creating new objects for each requests.
Can you explain it (preferably with examples 🙂 )?
As you said, you know the difference so I won’t get into that.
The reason you don’t want addSingleton for your repositories or services is because typically your repositories and services are considered "business logic" and "persistence logic". And in your business logic you might have some class level variables that are getting set. Those properties would not be different for every request, they would be shared across the requests. (think of them like static properties).
Imagine you have a user service that sets the username of the user making the request as a class level variable.
Now imagine Bob makes a request to the api. The username would be set to "Bob" . Now imagine at the same time, John makes a request to the api. The username would get set to "John". But because the user service is a singleton, both John and Bob are sharing the same instance, meaning Bob’s username would also be set to "John".
Imagine the exact same scenario as above, but this time when John makes a request, it does not override bobs username, because they are different instances.