Why is the use PerRequestLifetimeManager discouraged in the docs?

Mar 10, 2014 at 12:58 PM
According to the docs:
Although the PerRequestLifetimeManager lifetime manager works correctly and can help in working with stateful or thread-unsafe dependencies within the scope of an HTTP request, it is generally not a good idea to use it when it can be avoided, as it can often lead to bad practices or hard to find bugs in the end-user's application code when used incorrectly.
Wouldn't using this lifetime manager actually be safer in an environment that's intended to be stateless? If you're going to be using DbContext from EF, for instance, there's a chance that a prior request forgot to call DbContext.SaveChanges(). If the Unity container is reusing the instance of DbContext, your code that's intended to be stateless now becomes stateful unintentionally.
Mar 10, 2014 at 1:38 PM
Maybe it's because none of Unity's LifetimeManagers cleans up after itself. If instead of a PerRequestLifetimeManager you use a child container per request (about the only scenario child containers make sense to me) resolve all dependencies from that child and dispose of it at the end of the request you get proper clean-up behavior.
Mar 10, 2014 at 3:47 PM
I use per request to resolve EF DbContext, this is the only way i found to use all of the EF resources.

For example I have much more problems with the Per thread Lifetime Manager than with the Per request, a lot more problems with memory leak.
Mar 14, 2014 at 3:09 AM
@cb55555, this is just a caution that it should only be used where appropriate. DbContext/unit of work pattern in a web application is the typical case where this type of lifetime is needed.

Randy Levy
Enterprise Library support engineer
Support How-to