2

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() ;
    }
   ......
}
Eduard
  • 3,176
  • 3
  • 21
  • 31

2 Answers2

7

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.

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275
2

I figured out what was wrong. I forgot to configure my repository lifestyle to Transient. I dont quite understand how this is a problem though.

            container.Register(Component.For(typeof(IRepository<>))
                                    .ImplementedBy(typeof(Repository<>)).LifeStyle.Transient);

I wonder what is the default lifestyle then? I was reading in docs that it is singleton?! How could that be a problem?

Eduard
  • 3,176
  • 3
  • 21
  • 31
  • 1
    It's a problem because your ISession is per web request but you are keeping your repo around long after that. Hence the lifestyle closes ISession but repo tries to use it. – Henrik Jun 20 '11 at 20:29