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() ;
}
......
}
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.
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?
精彩评论