Search code examples
c#nhibernatecastle-windsorfacilities

Asp MVC problem configuring application with Windsor and NHibernate


Im having issues configuring application using windsor, facilities and nhibernate.

Im getting this exception:

ObjectDisposedException: Session is closed   

Shouldnt windsor take care of instantiating session per request and opening it when I have configuration like this? Could I miss some configuration? Here is my confuguration:

public class PersistenceFacility : AbstractFacility
{

    protected override void Init()
    {
        Configuration config = BuildDatabaseConfiguration();

        Kernel.Register(
            Component.For<ISessionFactory>()
                .LifeStyle.Singleton
                .UsingFactoryMethod(config.BuildSessionFactory),
            Component.For<ISession>()
                .LifeStyle.PerWebRequest
                .UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession()));
    }

    private Configuration BuildDatabaseConfiguration()
    {
        return Fluently.Configure()
            .Database(SetupDatabase)
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<RnUlice>())
            .ExposeConfiguration(ConfigurePersistence)
            .BuildConfiguration() ;
    }
   ......
}

Solution

  • If your Repository<T> gets a ISession in its constructor and it's singleton (default lifestyle), then it will only work in the first request you call your repository. In subsequent requests the repository will still have the same ISession as in the first call (because repository is singleton), but that session is now closed and invalid to use, therefore the error you see.

    This is why most of the time you don't want a singleton depending on other components with "shorter" lifestyles (like per-web-request or transient).

    See this article for a more thorough analysis of common lifestyle issues.