Monday, April 13, 2015

Using Ninject to inject HttpContext into an ASP.NET MVC Web Application

Injecting HttpContext into an ASP.NET MVC Web Application is a common requirement even with the latest version of ASP.NET MVC 5 since ASP.NET MVC still has underlying pinnings directly dependent on HttpContext.

If you search across the web, this is a somewhat difficult issue to tackle when dealing with Dependency Injection.

Though the solutions are pretty difficult to find on the Internet, fortunately, the actual implementations are relatively easy.

For example, to inject HttpContext into an ASP.NET MVC Web Application, you can use one of the following lines in your NinjectWebCommon.cs file:
kernel.Bind<HttpContext>().ToMethod(ctx => HttpContext.Current).InRequestScope();
kernel.Bind<HttpContextBase>().ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InRequestScope();

If you are interested in injecting something like the current User into your MVC Web Application, you can use something like this:

 


kernel.Bind<IIdentity>().ToMethod(ctx => HttpContext.Current.User.Identity);

If you need a class that is dependent on HttpContext (such as the creation and management of Cookies), you can use something like this:



kernel.Bind<ICookieManager>().To<CookieManager>().WithConstructorArgument("context", ctx => HttpContext.Current);

That is all there is to injecting HttpContext using Ninject in your ASP.NET MVC Web Applications! 



1 comment:

  1. What is the advantage of injecting HttpContext and HttpContextBase? How will I use them?

    ReplyDelete