If you have ever struggled with using HttpContext in your ASP.NET MVC Web Applications in regards to developing applications that can be easily tested, then you will be happy to know that this problem can be readily solved using HttpContextBase and an IoC container such as Ninject!
In my particular situation, I needed to use Cookies in my application therefore I created a class similar to the following:
Now the problem arose as to how to use an IoC container such as Ninject to handle injecting the proper HttpContext?
First of all, if you do not inject your HttpContext, you will receive an error something like shown below:
Well, there are 2 possible ways of accomplishing this:
The above method will inject HttpContext into any class that is dependent on HttpContextBase, therefore, making your development relatively easy to maintain going forward.
If you want to be more explicit about your HttpContextBase dependencies, you can instead do something like the following:
Therefore, as you can see, now you can easily inject an instance of HttpContext using HttpContextBase as well as easily Unit Test your applications using a Mocking Framework such as Moq by leveraging an interface such as the ICookieManager interface I have used in my above code samples.
That is all there is to it!!
In my particular situation, I needed to use Cookies in my application therefore I created a class similar to the following:
public class CookieManager : ICookieManager { private HttpContextBase _context; public CookieManager(HttpContextBase context) { _context = context; } public HttpCookie GetCookie(string cookieName) { HttpCookie cookie = null; if (_context != null) { cookie = _context.Request.Cookies[cookieName]; } return cookie; }//method: GetCookie() }
Now the problem arose as to how to use an IoC container such as Ninject to handle injecting the proper HttpContext?
First of all, if you do not inject your HttpContext, you will receive an error something like shown below:
Well, there are 2 possible ways of accomplishing this:
kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current));
The above method will inject HttpContext into any class that is dependent on HttpContextBase, therefore, making your development relatively easy to maintain going forward.
If you want to be more explicit about your HttpContextBase dependencies, you can instead do something like the following:
kernel.Bind<ICookieManager>().To<CookieManager>().WithConstructorArgument("context", ctx => new HttpContextWrapper(HttpContext.Current));
Therefore, as you can see, now you can easily inject an instance of HttpContext using HttpContextBase as well as easily Unit Test your applications using a Mocking Framework such as Moq by leveraging an interface such as the ICookieManager interface I have used in my above code samples.
That is all there is to it!!
No comments:
Post a Comment