AddTransient, AddScoped and AddSingleton Services Differences

后端 未结 8 1628
时光取名叫无心
时光取名叫无心 2020-11-22 13:36

I want to implement dependency injection (DI) in ASP.NET Core. So after adding this code to ConfigureServices method, both ways work.<

相关标签:
8条回答
  • 2020-11-22 14:17

    AddSingleton()

    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.

    AddScoped()

    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.

    AddTransient()

    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.

    0 讨论(0)
  • 2020-11-22 14:22
    • Singleton is a single instance for the lifetime of the application domain.
    • Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET.
    • Transient is a single instance per code request.

    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.

    0 讨论(0)
提交回复
热议问题