正如我在标题中所说,我想为每个 Web 请求实现会话。我的会话提供程序是这样配置的(我对更改此配置不感兴趣。)
public class SessionProvider
{
public static SessionProvider Instance { get; private set; }
private static ISessionFactory _SessionFactory;
static SessionProvider()
{
var provider = new SessionProvider();
provider.Initialize();
Instance = provider;
}
private SessionProvider()
{
}
private void Initialize()
{
string csStringName = "ConnectionString";
var cfg = Fluently.Configure()
....ommiting mappings and db conf.
.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
.BuildConfiguration();
_SessionFactory = cfg.BuildSessionFactory();
}
public ISession OpenSession()
{
return _SessionFactory.OpenSession();
}
public ISession GetCurrentSession()
{
return _SessionFactory.GetCurrentSession();
}
}
在 Global.asax.cs 中,我有以下与每个 web req 的会话相关的代码。
private static ISessionFactory SessionFactory { get; set; }
protected void Application_Start()
{
SessionFactory = MyDomain.SessionProvider.Instance.OpenSession().SessionFactory;
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var session = SessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
protected void Application_EndRequest(object sender, EventArgs e)
{
var session = CurrentSessionContext.Unbind(SessionFactory);
session.Dispose();
}
在调试我的 webapp 时出现错误:没有配置当前会话上下文。 ErrorMessage 引用 global.asax 行 CurrentSessionContext.Bind(session);
更新已
添加.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
,现在我在从我的控制器中检索数据时收到错误消息,如下所示
错误消息:会话已关闭!对象名称:'ISession'。
控制器代码:
using (ISession session = SessionProvider.Instance.GetCurrentSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
data = session.QueryOver<Object>()
...ommiting
transaction.Commit();
return PartialView("_Partial", data);
}
}