Helper类包装的MVC.NET Web开发的会议? [英] Helper class to wrap the Session for MVC.NET Web development?
问题描述
在<一个href=\"http://stackoverflow.com/questions/889516/session-null-in-asp-net-mvc-controller-constructors\">this后笔者建议实施一个包装器会话,以减轻测试和解耦控制器code。我会想获得关于如何实现这一目的的优良包装的想法。
我看到,在 $ C $的CProject 有一个样本,但它看起来比什么,我需要更多的方式。
编辑1:
确定。由于约书亚我有实施和简单的会话的辅助类。我在这里张贴类,让您的意见,看看你会补充一下。
公共接口ISessionHelper
{
吨得到&LT; T&GT;(字符串键);
}公共类HttpContextSessionHelper:ISessionHelper
{
私人只读的HttpContext _context; 公共HttpContextSessionHelper(HttpContext的背景下)
{
_context =背景;
} 公众吨得到&LT; T&GT;(字符串键)
{
对象值= _context.Session [关键] 返回值== NULL?默认(T)(T)值;
}
}
在控制器我有这样的事情:
私人只读ISessionHelper _sessionHelper; 公众的HomeController(ISessionHelper会话)
{
_sessionHelper =会议;
} 公共HomeController的()
{
_sessionHelper =新HttpContextSessionHelper(System.Web.HttpContext.Current);
}
其中的<一个href=\"http://stackoverflow.com/questions/889516/session-null-in-asp-net-mvc-controller-constructors/1020465#1020465\">other答案对这个问题曾与此评论有一个很好的简单包装的例子网站。有人评论所作 murki 。
In this post the author recommends implementing a Wrapper for the session to ease testing and decoupling the controller code. I will like to obtain ideas on how to implement a good wrapper for this purpose.
I see that in CodeProject there is one sample but it looks way more than what I need.
EDIT 1:
Ok. Thanks to Joshua I have implement and simple session helper class. I am posting the class here to get your opinion and see if you will add something.
public interface ISessionHelper
{
T Get<T>(string key);
}
public class HttpContextSessionHelper : ISessionHelper
{
private readonly HttpContext _context;
public HttpContextSessionHelper(HttpContext context)
{
_context = context;
}
public T Get<T>(string key)
{
object value = _context.Session[key];
return value == null ? default(T) : (T)value;
}
}
In the controller I have something like this:
private readonly ISessionHelper _sessionHelper;
public HomeController(ISessionHelper session)
{
_sessionHelper = session;
}
public HomeController()
{
_sessionHelper = new HttpContextSessionHelper(System.Web.HttpContext.Current);
}
One of the other answers to that question had a comment with this website that has a good simple wrapper example. The comment was made by murki.
这篇关于Helper类包装的MVC.NET Web开发的会议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!