Search code examples
c#asp.net-coredependency-injection

Why use AddScoped() instead of AddSingleton()?


Why I should use AddScoped() for my repositories or services? Why not AddSingleton()? 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 :) )?


Solution

  • 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).

    Example:

    Imagine you have a user service that sets the username of the user making the request as a class level variable.

    Singleton logic:

    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".

    Scoped logic:

    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.