2

I need to setup session management in MVC. what is the correct way of doing so? How to setup nhibernate session management in mvc using structuremap so I don't get:

Session is closed or Using a single Session in multiple threads is likely a bug.

My current configuration is: in GlobalAssax:

protected void Application_Start()
    {
        ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
        Bootstrapper.ConfigureStructureMap();
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

    }

in my BootStrapper I do:

var cfg = NHibernateManager.Configuration(assembly);
For<Configuration>().Singleton().Use(cfg);
For<ISessionFactory>().Singleton().Use(cfg.BuildSessionFactory());
For<ISession>().HttpContextScoped().Use(ctx => ctx.GetInstance<ISessionFactory>().OpenSession());

I Inject ISession into repositoryes that I use in application layer.

Edit: What happens if I do this?: For().LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.PerRequest)).Use(ctx => ctx.GetInstance().OpenSession());

Luka
  • 4,075
  • 3
  • 35
  • 61
  • Are you calling Dispose on or having a using clause around a session anywhere in your application? If so remove it, since you're letting StructureMap handle the lifecycle. – PHeiberg Sep 09 '10 at 11:32

1 Answers1

0

Have you added a dispose for the session?

//In Global.asax.cs
protected void Application_EndRequest()
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

Otherwise it looks correct.

PHeiberg
  • 29,411
  • 6
  • 59
  • 81
  • Yes, now if I added the dispose in the EndRequest , I get Session Is closed exception on some query. If I don't add the above dispose, I get threading exception. – Luka Sep 09 '10 at 11:08
  • @Luka - Have you looked in the NHibernate logs and seen what's going on? http://stackoverflow.com/questions/743323/nhibernate-enabling-log4net – PHeiberg Sep 09 '10 at 11:29
  • Yes, And there are no errors in it. The last lines says: Aggressively releasing database connection, Closing connection. No connection is being obtained for my opperation – Luka Sep 09 '10 at 13:13
  • Sorry, I'm out of ideas. I guess you have to trace/debug through the application and find out what closes the session if the problem occurs when debugging. – PHeiberg Sep 09 '10 at 13:50
  • Errors were caused by Automapper – Luka Sep 20 '10 at 17:52