2

I am using Ninject, NHibernate, ASP.NET MVC3 and repository pattern. The module binding in Ninject is as following.

Bind<ISessionFactory>().ToProvider(new SessionFactoryProvider()).InSingletonScope();
Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();

The question is should the repository take an ISession or ISessionFactory. If it takes an ISessionFactory then in the repository I can open a session when necessary and close it after use. If it takes an ISession, the repository uses it directly. But I am wondering if the session is closed properly.

h--n
  • 5,903
  • 4
  • 31
  • 32
  • Have a look around - think this has been addressed before. Cant find it though, best I got was http://stackoverflow.com/questions/1296901/injecting-isession-into-my-repositories-using-structuremap-in-a-asp-net-mvc-appli/1298469#1298469 – Ruben Bartelink Mar 07 '11 at 16:10
  • One reason I say this is e.g. that having the Dispose happen at a time decided by the Container's integration with MVC may or may not yield a good error path for a resulting exception -- often you'll want to Flush explicitly in a managed way – Ruben Bartelink Mar 07 '11 at 17:01
  • Hi @Ruben, thanks. AS you said, when Dispose is called depends on the container's integration with MVC. And I prefer to do it explicitly in a managed way. – h--n Mar 18 '11 at 14:06

2 Answers2

2

I usually open a new session and transaction on the beginning of a request and commit/close it on the end.

Look at this post on nhibernate.info. This post goes beyond your needs, I think it will help you a lot. Take a better look at the custom HttpModule he wrote. That's just an example, you can search at Google and find lots of similar implementations.

Frédéric
  • 9,364
  • 3
  • 62
  • 112
goenning
  • 6,514
  • 1
  • 35
  • 42
  • Thanks, the link you give helps a lot to understand. I'd also like to open/commit/close explicitly. – h--n Mar 18 '11 at 14:09
2

So your session is configured as per-request. That means, it is opened at the beginning of the request, and closed at the end by the container. And this is probably a good idea. If you try to reopen(or close) session manually, I guess it will throw exception. Just have ISession injected into repository.

driushkin
  • 3,531
  • 1
  • 24
  • 25
  • Hi, Thanks for the answer. But as Ruben said, I think when the Dispose is called depends on the container's integration with MVC. I don't think Ninject does it. But the extention Ninject.Web.Mvc does it. Anyway, I'd prefer to do it explicitly for now. – h--n Mar 18 '11 at 14:17