Search code examples
ninjectcastle-windsorautofac

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?


Solution

  • 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