Unity: HttpRequest LifetimeManager?

Topics: General discussion
Oct 24, 2008 at 10:18 PM
Edited Oct 24, 2008 at 10:23 PM
I need one instance of an object to be created per HttpRequest in my ASP.NET MVC application. I think I can accomplish this with a custom LifetimeManager that stores instances of types inside of HttpContext.Current. Do I understand the way a LifetimeManager works? So if I have the following code, will this function for all requests for a type?


    public class HttpRequestLifetimeManager : LifetimeManager
        private readonly Guid key;

        public HttpRequestLifetimeManager()
            key = Guid.NewGuid();

        public override object GetValue()
            return HttpContext.Current.Items[key];

        public override void SetValue(object newValue)
            HttpContext.Current.Items[key] = newValue;

        public override void RemoveValue()

In Global.asax under Application_Start()

// Any request for a SystemEntityDatabase data context will provide one instance per HttpRequest
container.RegisterType<SystemEntityDatabase, SystemEntityDatabase>(new HttpRequestLifetimeManager());

Oct 24, 2008 at 10:34 PM
So, one other issue. I really need to have objects disposed of at the end of an HttpRequest. Is there any way to ensure when the HttpContext is destroyed, that objects in its Items are disposed of properly? I think the above code might be setting me up for some issues.
Oct 27, 2008 at 1:26 AM

you can try reading through this link.


also. you can post this inquiry to the unity forum.


Hope this helps.