Is it a good practice to access a HttpContext session outside the controller in separate helper class?
====================
Should the controller take all the responsibility of getting the data from the session and transfer to a helper class
Example
HomeController : BaseController
{
var value1 = Httpcontext.Session["key1"];
var value2 = Httpcontext.Session["key2"];
var val...
CallAMethod(value1,value2,val...);
}
Or should it mock HttpContextBase and use it as in the following?
HomeController : BaseController
{
//Use Dependency Injection pattern
CallAMethod(base.SessionWrapper);
}
Implementation of ISessionWrapper is
public interface ISessionWrapper
{
T GetFromSession<T>(string key);
SetInSession(string key, object value);
}
public class HttpContextSessionWrapper : ISessionWrapper
{
private T GetFromSession<T>(string key)
{
return (T) HttpContext.Session[key];
}
private void SetInSession(string key, object value)
{
HttpContext.Session[key] = value;
}
}
public class BaseController : Controller
{
public ISessionWrapper SessionWrapper { get; set; }
public BaseController()
{
SessionWrapper = new HttpContextSessionWrapper();
}
}
Apparently you want to have some testability in your code (after all that's why you're going through the burden of creating an ISessionWrapper).
Both approaches have ups and downs.
Using the HttpContext directly
Quicker to develop
Need some thoughts on testing class. Nemely the ability to emulate a HttpContext. Doable with library available on the NET.
Using dependency injection (ISessionWrapper):
Slower to develop
Need to "reinvent the wheel" regarding access to the HttpContext
A lot more code to write and mantain
So, I would ponder the pros and cons of both approaches and decide depending on my goals.
However, personally, I would choose the path that require a lot less code to write.
Edited to Add
In reply to the heart of the question (after a nag in from the OP) the controller should always manage the data gathering before passing them to the actuators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With