views:

52

answers:

1

Hi, 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());

A: 

Have you added a dispose for the session?

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

Otherwise it looks correct.

PHeiberg
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
@Luka - Have you looked in the NHibernate logs and seen what's going on? http://stackoverflow.com/questions/743323/nhibernate-enabling-log4net
PHeiberg
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
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
Thanks anyway I will try
Luka
Errors were caused by Automapper
Luka