3

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?

7
  • 1
    ayende.com/blog/4809/…
    – dotjoe
    Jan 31, 2013 at 17:04
  • 2
    you need to make the factory static, but check out that link to see example of how to wrap each action in a transaction.
    – dotjoe
    Jan 31, 2013 at 17:05
  • The Post references a type SessionController, where can I find this?
    – Chazt3n
    Jan 31, 2013 at 17:10
  • SessionController is simply a base controller that you create with a public ISession property named Session. Then you make your controllers inherit from base controller and use that ISession in each action method.
    – dotjoe
    Jan 31, 2013 at 17:14
  • The type or namespace name 'SessionController' could not be found (are you missing a using directive or an assembly reference?)
    – Chazt3n
    Jan 31, 2013 at 17:15

2 Answers 2

1

You need to make the SessionFactory static so all controllers will use the same instance. Ayende has a good blog post for an example of how to do that and also how to wrap actions in a transaction.

public class SessionController : Controller
{
    public HttpSessionStateBase HttpSession { get { return base.Session; } }
    public new ISession Session { get; set; }
}

//you could put this class in the same physical file as the SessionController.cs 
//since they are tightly coupled to each other
public class NHibernateActionFilter : ActionFilterAttribute
....

then change your AccountController to...

public class AccountsController : SessionController
{
    public ActionResult Index()
    {
         //Session is primed and ready for use
    }
}

lastly make sure to register the action filter in global.asax

1
  • Thank you sir, really appreciate you taking your time to explain this. It is a very simple approach, but much like brain surgery, it's very helpful to have a helping hand to grasp fully
    – Chazt3n
    Jan 31, 2013 at 19:49
0

This is how I personally solved my problem (with the help of DotJoe and others on this site)

Global.asax.cs

   public static ISessionFactory SessionFactory =
             SessionProvider.BuildSessionFactory();

    protected void Application_Start()
    {       
        SessionFactory.OpenSession();
    }

Controller

  public ActionResult ReadAccounts([DataSourceRequest] DataSourceRequest request)
    {
        DataSourceResult result;

        using(ISession session = TRX.CRM.Dashboard.Web.UI.MvcApplication.SessionFactory.OpenSession())
        {
            using (ITransaction tx = session.BeginTransaction())
            {
                var customers = session.Query<Accounts>().Where(a => a.Deleted == false).AsNoTracking();
                //from customer in session.Query<Accounts>().AsNoTracking()
                //                where !customer.Deleted
                //                select customer;
                result = customers.ToDataSourceResult(request);
                tx.Commit();
            }
        }
        return Json(result, JsonRequestBehavior.AllowGet);
    }

I then created a class in a folder called Utilities:

SessionFactory.cs

public class SessionProvider  
{
   public static ISessionFactory BuildSessionFactory()
   {
     return Fluently.Configure()
          .Database(MySQLConfiguration.Standard.ConnectionString(
          c => c.FromConnectionStringWithKey("DashboardModels")
      ))
     .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Accounts>())
     .BuildSessionFactory();

    }
}

I hope this code can help anyone else who needs to convert from EF to NHibernate in a pinch.

This has kept my memory management in a pretty large application with 145 users to a little over 450,000kb. (down from 600,000kb using EF) a testament to the scalability of NHibernate.

NHProf is highly recommended as well. It has great suggestions and will provide resources for your specific problem.

If you're going to use Mono, This is the way to go in my opinion.

1
  • Whoever rejected the edits are introducing memory leaks into reader's of this posts code. Good job.
    – Chazt3n
    Jun 21, 2014 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.