What is difference between addtransient and addscoped in .net core?

Dung Do Tien Oct 24 2021 129

I'm curently upgrade project .net  from .net 4.6 to .net core 3.1. I still feel confuse between AddTransient() and AddScoped() of DI in Asp.Net Core. I don't know really difference between them.

I have two service is IMemberQuizBoFE and ICommentBoFE and I try register as below it's working WELL for me:

services.AddScoped<IMemberQuizBoFE, MemberQuizBoFE>();
services.AddTransient<ICommentBoFE, CommentBoFE>();

And I try as below it also working WELL:

services.AddTransient<IMemberQuizBoFE, MemberQuizBoFE>();
services.AddTransient<ICommentBoFE, CommentBoFE>();

And I try as below it also working WELL:

services.AddScoped<IMemberQuizBoFE, MemberQuizBoFE>();
services.AddScoped<ICommentBoFE, CommentBoFE>();

:D I really difficult to understand, What case should use AddScoped and AddTransient?

Anyone can explaint detail for me?

Thanks for any explaintation.

Have 2 answer(s) found.
  • U

    Unnop Niratiam Oct 24 2021

    - AddScoped: Follow by url request.

    - AddTransient:  Depend on service initialize.

    Don't forget DI inject default throught by Constructor of services or controllers. So any one Constructor to be called Transient will be re-instance service. You can see diagram below:

    What is difference between addtransient and addscoped in .net core?

    I hope it helpful for you.

  • D

    Dorian G. Ramos Oct 24 2021

    2.5.1. Transient 

    Transient lifetime services are created each time they're requested from the service container. This lifetime works best for lightweight, stateless services. So you can understand that a class can be instanced many times for one request if you have many components call that class.

    * Note: You need to consider when to use this lifetime because if you use it many times in a request maybe it makes the decrease time load page.

    2.5.2. Scoped

    Scoped lifetime services are created once per client request. In web apps process requests, scoped services are disposed of at the end of the request.

    2.5.3. Singleton

    Singleton lifetime services are created once when the application starts, it only destroys when that application stops.

    For more information you can refer Dependence Injection in Asp.Net Core.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close