Jonas Stawski

Everything .NET and More

HttpContextBase and Dependency Injection

I was just hunt down by a minor bug in my code and couldn’t figure out what was happening. I’m using Dependency Injection to inject the HttpContextBase into a service call so I can more easily unit test it. So I was setting it up like this:

   1: ObjectFactory.Initialize(x =>
   2:     {
   3:         x.For<HttpContextBase>().Use(new HttpContextWrapper(HttpContext.Current));
   4:     });

I was then getting Object reference not set to an instance of an object. So I started debugging and saw that the Url property of the Request was null, which made no sense. Farther investigation revealed this question in StackOverflow.com, where Joshua Flanagan specifically mentions that the registration should happen with a lambda, otherwise the HttpContext available at registration time will be used as a singleton in every creation of the Service.

WOW! Amazing! I then confirmed that the context passed in to my service call was different than HttpContext.Current. So to solve this I changed the above code to this:

   1: x.For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current));
Happy Programming!

Add comment

biuquote
Loading