比方说,我有一个辅助类是这样的:这种每个请求的上下文实现是否安全?
public static class RequestHelper {
private const String DbContextKey = "DbContext";
public static DbContext CurrentDbContext {
get { return HttpContext.Current.Items[DbContextKey] as DbContext; }
set { HttpContext.Current.Items[DbContextKey] = value; }
}
}
然后在我的Global.asax.cs
我:
protected void Application_BeginRequest() {
RequestHelper.CurrentDbContext = new DbContext("some_conn_string_name");
}
这是设计在所有请求安全吗?如果我总是通过RequestHelper.CurrentDbContext
进行数据访问,我会遇到任何问题吗?
我问的原因是我已经看到依赖于依赖注入的context-per-request的更复杂的实现。我觉得我必须错过一些明显的东西,而且我恐怕只有在应用程序中拥有足够多的用户时才会注意到。
如果你没有任何长期生活要求,它应该没问题。 – leppie 2013-03-19 18:34:23
不要忘记在'EndRequest'中处理上下文 – 2013-03-19 18:41:57