Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transient vs per webrequest lifestyle, what constitutes a web request?

What are the differences between these two life cycles?

Let's say my MVC controller is being supplied with an object that was configured as transient, then when someone visits a method in that controller a new instance is injected in the class constructor and then the method is called.

Each and every get/post to the controller is a new request, right? If so, then I don't see any difference between the two.

Can someone explain / provide an example of when you would use one vs the other?

like image 395
WhiskerBiscuit Avatar asked Mar 22 '14 07:03

WhiskerBiscuit


2 Answers

The difference between Transient and Web Request is negligible when registering your Controller types as Transient, since -as you said- each request gets its own Controller and only one controller instance for that type is resolved in that request.

Things start to get interesting when there's a dependency in the Controller's object graph that is refered by multiple components. A good example for when this might happen is with a Unit of Work (such as Entity Framework's DbContext). Multiple services inside the object graph might need that same Unit of Work, and for the correctness of your application they all need the same instance during that request; but each request must get a new Unit of Work instance.

To learn more about when and when not to have one Unit of Work Per Request or not, read this: One DbContext per web request… why?

like image 91
Steven Avatar answered Nov 15 '22 01:11

Steven


You cannot fault your DI tool for failing to distinguish between cases it doesn't know. PerWebRequest scope is a scope that lasts from the beginnning of a webcall to the end of the webcall. Transient lives as long as you hold a reference to the resolved entity (usually the caller's lifetime).

Of course if the resolving entity has the same lifespan as the request you won't see any difference. A PerWebRequest lifespan lives from the beginning of a request to its end. A Transient lifespan lives according to reference held on it; if you need some logging completely dependent on the current webrequest you would set a PerWebRequest lifespan. The controller that handles the request would get a Transient lifespan since its work finished it wouldn't be needed anymore

like image 4
samy Avatar answered Nov 15 '22 03:11

samy