I want to implement dependency injection (DI) in ASP.NET Core. So after adding this code to ConfigureServices
method, both ways work.<
AddSingleton() creates a single instance of the service when it is first requested and reuses that same instance in all the places where that service is needed.
In a scoped service, with every HTTP request, we get a new instance. However, within the same HTTP request, if the service is required in multiple places, like in the view and in the controller, then the same instance is provided for the entire scope of that HTTP request. But every new HTTP request will get a new instance of the service.
With a transient service, a new instance is provided every time a service instance is requested whether it is in the scope of the same HTTP request or across different HTTP requests.
Normally the code request should be made through a constructor parameter, as in
public MyConsumingClass(IDependency dependency)
I wanted to point out in @akazemis's answer that "services" in the context of DI does not imply RESTful services; services are implementations of dependencies that provide functionality.