Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top