NHibernate, dependency injection. Close ISession properly

我的梦境 提交于 2020-01-01 06:55:14

问题


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.


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/5221620/nhibernate-dependency-injection-close-isession-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!