Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am trying to understand when to use
AddTransient() and AddScoped()
specially in the web api.

I go through the many article on these topic mostly example is showing the object ids on veiw page. what if i am using the web api.

should i use AddTransient for ICustomerService or ICustomerRepository as AddTransient?


AddScoped() - A new instance of a Scoped service is created once per request within the scope. For example, in a web application it creates 1 instance per each http request but uses the same instance in the other calls within that same web request.
Please help me to understand the Scope of request

in above defination i am trying to understand the "
uses the same instance in the other calls within that same web request
"
does it fit in case of .net core rest api project.

What I have tried:

I Create a api controller and fetch the Hashcode of service object injected in constructor of Api controller.
Posted
Updated 18-May-21 21:46pm

1 solution

Scope is a whatever process between HTTP request received and HTTP response sent.
Use scoped if a service is related to a request (e.g. user) and is heavy to build (e.g. fetching user profile that in turn will be used for the entire response process).
Use scoped if service is used for inter service communication for the same request. (e.g. in case of parallel processing for coordination/progress/state etc.)
Use transient otherwise.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900