Right now, my session Factory lives in my controllers, and is being created over and over again. How can I create one that is shared between controllers?
public class AccountsController : Controller
{
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MySQLConfiguration.Standard.ConnectionString(
c => c.FromConnectionStringWithKey("DashboardModels")
))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Accounts>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Notes>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Sales_Forecast>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ChangeLog>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Tasks>())
.BuildSessionFactory();
}
ISessionFactory sessionFactory = CreateSessionFactory();
...
...
EDIT I've added the SessionController Class like so:
public class SessionController : Controller
{
public HttpSessionStateBase HttpSession
{
get { return base.Session; }
}
public new ISession Session { get; set; }
}
and created a new SessionFactory Utility Class
public class NHibernateActionFilter : ActionFilterAttribute
{
private static readonly ISessionFactory sessionFactory = BuildSessionFactory();
private static ISessionFactory BuildSessionFactory()
{
return new Configuration()
.Configure()
.BuildSessionFactory();
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var sessionController = filterContext.Controller as SessionController;
if (sessionController == null)
return;
sessionController.Session = sessionFactory.OpenSession();
sessionController.Session.BeginTransaction();
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var sessionController = filterContext.Controller as SessionController;
if (sessionController == null)
return;
using (var session = sessionController.Session)
{
if (session == null)
return;
if (!session.Transaction.IsActive)
return;
if (filterContext.Exception != null)
session.Transaction.Rollback();
else
session.Transaction.Commit();
}
}
}
Quesions/Concerns: Using FluentNhibernate, how should I configure my new SessionFactory Class, and how do I create and use a transaction in my controller?