AddTransient, AddScoped and AddSingleton Services Differences

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

    Which one to use

    Transient

    • since they are created every time they will use more memory & Resources and can have the negative impact on performance
    • use this for the lightweight service with little or no state.

    Scoped

    • better option when you want to maintain state within a request.

    Singleton

    • memory leaks in these services will build up over time.
    • also memory efficient as they are created once reused everywhere.

    Use Singletons where you need to maintain application wide state. Application configuration or parameters, Logging Service, caching of data is some of the examples where you can use singletons.

    Injecting service with different lifetimes into another

    1. Never inject Scoped & Transient services into Singleton service. ( This effectively converts the transient or scoped service into the singleton.)
    2. Never inject Transient services into scoped service ( This converts the transient service into the scoped. )

提交回复
热议问题