2
votes

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.

2
Have a look around - think this has been addressed before. Cant find it though, best I got was stackoverflow.com/questions/1296901/… - Ruben Bartelink
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
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

2 Answers

2
votes

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.

1
votes

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.