AddTransient, AddScoped and AddSingleton Services Differences

后端 未结 8 1639
时光取名叫无心
时光取名叫无心 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: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.

提交回复
热议问题