My base controller class, BaseController
, is inherited by public-facing controllers to access a shared data context between requests with LINQ-to-SQL.
- Am I accessing my data context in an efficient and safe way by storing it in
HttpContext.Current.Items
for each HTTP request?
DataContextHelper
class
internal static class DataContextHelper
{
public static MyDataContext CurrentContext
{
get
{
if (HttpContext.Current.Items["MyDataContext"] == null)
{
MyDataContext context = new MyDataContext();
HttpContext.Current.Items["MyDataContext"] = context;
}
return (MyDataContext)HttpContext.Current.Items["MyDataContext"];
}
}
}
BaseController
class:
public class BaseController : Controller
{
protected MyDataContext db
{
get {
return DataContextHelper.CurrentContext;
}
}
}
HomeController
class:
[HandleError]
public class HomeController : BaseController // inherits db member
{
public ActionResult SomeAction(string id)
{
User user = db.Users.First(u => u.UserId == id);
// ... do stuff
db.SubmitChanges();
}
}