I am trying to use fluent with session per request. I am following a "recipe" from nhibernate cookbook however it uses the nhibernate config file.
I am not sure what is better but right now I am sticking with fluent config just because I would not know how to set the nhibernate config file to use fluent mapping and vanilla nhibernate mapping(hbm files).
namespace Demo.WebUI
{
public class MvcApplication : NinjectHttpApplication
{
public static ISessionFactory SessionFactory { get; private set; }
protected override void OnApplicationStarted()
{
SessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(
c => c.FromConnectionStringWithKey("test")))
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf
<Demo.Framework.Data.NhibernateMapping.UserMap>())
.ExposeConfiguration(BuidSchema)
.BuildSessionFactory();
}
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);
SessionFactory.Dispose();
}
}
}
As you can see in the Begin_Request the books tutorial had
CurrentSessionContext.Bind(session);
However if I use this it throws a error since I don't have the nhibernate config file in use.
So how do I change it to use fluent configuration? Or do I not even need to do this step?(ie is it done internally?)
You need to tell NHibernate how to handle the session context. The following might work:
Fluently.Configure()
...
.ExposeConfiguration(cfg => cfg.SetProperty(
Environment.CurrentSessionContextClass,
"web")
Also, unrelated to this: you are disposing the SessionFactory on EndRequest. That is an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With