AddTransient, AddScoped and AddSingleton Services Differences

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

    In .NET's dependency injection there are three major lifetimes:

    Singleton which creates a single instance throughout the application. It creates the instance for the first time and reuses the same object in the all calls.

    Scoped lifetime services are created once per request within the scope. It is equivalent to a singleton in the current scope. For example, in MVC it creates one instance for each HTTP request, but it uses the same instance in the other calls within the same web request.

    Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services.

    Here you can find and examples to see the difference:

    ASP.NET 5 MVC6 Dependency Injection in 6 Steps (web archive link due to dead link)

    Your Dependency Injection ready ASP.NET : ASP.NET 5

    And this is the link to the official documentation:

    Dependency injection in ASP.NET Core

提交回复
热议问题