Pergunta

I'm trying to set NHibernate to handle my sessions per web request. I have a project that initializes my Session when any of my repositories are used. I would like to know the best way to manage my session per each web request. Because my architecture is decoupled, I would like to avoid Opening the session and closing the session in my web project. Is there a good way to handle this without requiring the web project to know about the existence of NHibernate?

This is my request flow:

Web Request -> ASP.NET MVC 3 -> Controller -> Service -> Repository (Opens Session) -> NHibernate -> Database -> Back to MVC and out.

Foi útil?

Solução

Have a look at S#arp Architecture. It's a framework that wraps NHibernate and provides this for you, as well as some other features. You can also do this with a dependency injection container like Castle Windsor or Ninject. (S#arp uses Castle Windsor).

If you want to do this on your own, you would need to create an HttpModule to open and close the session for you at the start and end of each web request. At the start of a request, the module would open a session, and stash it away in the HttpContext.Items, which is per-web-request storage. Your repositories would get the session from here while processing the request. (For a clean design, create an interface ISessionManager that the repositories use, and an implementation that accesses the per-request storage. Then it's unit-testable.) Finally the module would flush and close the session at the end of a request. I did this once on an NHibernate project, and though it was educational, it was a lot of work.

S#arp is a large framework that dictates a lot of the application structure. If you don't want to go that far, look at Castle Windsor to cleanly abstract this away for you. All you need to do (more or less) is configure the container to instantiate the repositories with a per-request NHibernate session object as a constructor parameter. If you really want to learn how, build your own HttpModule, but I recommend using a framework in production.

Outras dicas

Here is great article how to achieve session-per-request using IoC container (Castle Windsor) http://blog.xelibrion.com/journal/2011/4/16/nhibernate-session-management-in-aspnet-mvc-application.html

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top