4

Is there a recommended approach for injecting Http/Request/Controller context in an ASP.NET MVC application?

Previously I've only done this with HttpContext like so (I'm using StructureMap):

For<HttpContextBase>().Use(ctx => new HttpContextWrapper(HttpContext.Current));

However, in some cases I also need to get access to the request context. Rather than building this manually, it would be nice to have it injected. A good example would be injecting a UrlHelper (requires RequestContext and RouteCollection).

Thanks

Ben

Ben Foster
  • 34,340
  • 40
  • 176
  • 285

1 Answers1

4

You might want to consider whether you really want to depend on those context objects directly (they tend to make things that depend on them hard to test). That said, you are on the right track:

For<RequestContext>().Use(ctx => HttpContext.Current.Request.RequestContext);
For<RouteCollection>().Use(ctx => RouteTable.Routes);
Robin Clowers
  • 2,150
  • 18
  • 28
  • Hi Robin, I generally only have these dependencies for purely contextual objects, for example a SiteContext context that abstracts access to things like current user etc. I can always mock HttpContextBase anyway. I did find this post too that looks interesting - http://kozmic.pl/2010/05/22/contextual-controller-injection-in-asp-net-mvc-with-castle-windsor/ – Ben Foster Mar 29 '11 at 16:32
  • why does it make it harder to test, they are injected so can jsut be mocked in ? (I am about to do this, well I was about to do this) – NimChimpsky Apr 09 '14 at 15:48