开发者

NHibernate, dependency injection. Close ISession properly

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜