Scoped vs Transient in DI

shenbagapandiyan p 21 Reputation points
2020-12-04T04:43:52.187+00:00

The scope will reuse the object whatever has been created within the request.

Transient will create a new instance within the request.

What is the exact use case for scope vs transient on the high-end application in terms of the service layer and repository layer?

How Dbcontext will behave on CRUD operation using scope vs transient?

How it will be increased and decrease the application perfomance?

Developer technologies | .NET | .NET Runtime
0 comments No comments
{count} votes

Accepted answer
  1. Jerry Cai-MSFT 991 Reputation points
    2020-12-04T07:36:25.317+00:00

    Hi,shenbagapandiyanp

    Does this post also related to ef core? And what is your project type, could you please shared some related code?

    Transient works best for lightweight, stateless services. If you don't use any other injected services which are also using your DBContext there's

    no difference between scoped and transient.

    Following links may help you, you can view more details about transient and scoped:

    does-dbcontext-registered-as-scoped-or-transient-affect-in-closing-database

    addtransient-addscoped-and-addsingleton-services-differences

    dependency-injection

    Best Regards,
    Jerry Cai


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Mustafa 1 Reputation point
    2023-02-22T11:19:19.68+00:00

    Transient:  The object is created each time they're injected. Transient objects are always different; a new instance is provided to every controller and every service.

    Scoped: Scoped lifetime indicates that services are created once per client request.

    Singleton: Objects are created ‎in the first time they're requested. Singleton objects are the same for later requests.

    0 comments No comments

  2. Bruce (SqlWork.com) 77,851 Reputation points Volunteer Moderator
    2023-02-27T17:21:56.3733333+00:00

    it depends on the use case. typically a dbcontext is only injected into a controller / razor page so it makes no difference. but if you also need the dbcontext in middleware, then you probably do not want them using the same dbcontext, as one can use at a time. in this case you want Transient.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.