How can I make every HTTP request start a transaction, and in the end I commit transactions?
I already use InRequestScope for my sessions and have this for my ninject.
public class NhibernateSessionFactory
{
public ISessionFactory GetSessionFactory()
{
ISessionFactory fluentConfiguration = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("ConnectionString")))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Map>().Conventions.Add(ForeignKey.EndsWith("Id")))
.ExposeConfiguration(cfg => cfg.SetProperty("adonet.batch_size", "20"))
.BuildSessionFactory();
return fluentConfiguration;
}
private static void BuidSchema(NHibernate.Cfg.Configuration config)
{
new NHibernate.Tool.hbm2ddl.SchemaExport(config).Create(false, true);
}
}
public class NhibernateSessionFactoryProvider : Provider<ISessionFactory>
{
protected override ISessionFactory CreateInstance(IContext context)
{
var sessionFactory = new NhibernateSessionFactory();
return sessionFactory.GetSessionFactory();
}
}
public class NhibernateModule : NinjectModule
{
public override void Load()
{
Bind<ISessionFactory>().ToProvider<NhibernateSessionFactoryProvider>().InSingletonScope();
Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();
}
Edit
I know that ninject is set to OnActivation and OnDeactivation
but what I find strange is this.
begin transaction with isolation level: Unspecified
select TOP ( 1 ) student0_.StudentId
begin transaction with isolation level: Unspecified
select TOP ( 1 ) student0_.StudentId
select courseperm0_.PermissionId
begin transaction with isolation level: Unspecified
commit transaction
SELECT this_.TaskReminderId as TaskRemi1_13_0_
SELECT this_.ReminderId as ReminderId0_2_,
SELECT this_.ReminderId as ReminderId8_2_,
The above is from the profiler, but I deleted most of the request as I did not think it was relivent to the problem.
See how all of a sudden for the operator 8,9,10 he does not commit the transaction. But before that he did 3. I do not understand this.
Edit 2
I found this post
.OnActivation(session =>
{
session.BeginTransaction();
session.FlushMode = FlushMode.Commit;
})
This seems to help my problem a bit (there is still a problem with lazy loading). I wonder why this works, and if something might go wrong using it.