As I said in the title I want to implement session per web request. My session provider is configured like this (I'm not interested in changing this conf.)
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();
}
}
Inside Global.asax.cs I have following code related to session per 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();
}
On debuggin my webapp I get error: No current session context configured. ErrorMessage referenced to global.asax line CurrentSessionContext.Bind(session);
Updated
Added .ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
and now I have error message on retrieving data from my controller like this
Error message: Session is closed! Object name: 'ISession'.
Controller code:
using (ISession session = SessionProvider.Instance.GetCurrentSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
data = session.QueryOver<Object>()
...ommiting
transaction.Commit();
return PartialView("_Partial", data);
}
}
1st Question
You need to configure it in your nhibernate configuration section:
Also I currently do something like this:
2nd Question
Please look at the following article to modify configuration fluently: currentsessioncontext fluent nhibernate how to do it?
3rd Question
You are closing your session twice.
closes your session. Then you did it again in
Application_EndRequest
. If you have another question please post a new question.