ASP.NET MVC and NHibernate connection

I just started learning NHibernate.

For the past few months, I've been using IoC / DI (structure map) and the repository pattern, and this has made my applications much more loosely coupled and easier to test.

When switching persistence level in NHibernate, I decided to stick with my repos. I am currently creating a new session for every method call, but of course that means I cannot take advantage of lazy loading.

So I want to implement session-per-request, but doing so will make my web project depend on NHibernate (maybe it's not that bad?). I was planning to inject ISession into my repos, and create and delete sessions on beginrequest / endrequest events (see http://ayende.com/Blog/archive/2009/08/05/do-you-need-a-framework. aspx )

Is this a good approach? Presumably I cannot use session per request without NHibernate reference in my web project?

If a web project that relies on NHibernate raises my following (multiple) questions - why even bother with the repository? Since my web application calls services that talk to repositories, why not ditch the repos and just add my NHibernate status code inside the services? And, finally, is there any need to divide into so many projects. Is the web design and infrastructure design sufficient?

I realize I strayed a bit from my original question, but it seems that everyone seems to have their own opinion on these topics. Some people use the storage pattern with NHibernate, some do not. Some people attach their mapping files to related classes, others have a separate project for this.

Thanks a lot Ben

+2


a source to share


3 answers


I would not depend on NHibernate's business logic. I wrote a (more or less simple) class to create a session in context:

using (TransactionService.CreateTransaction())
{
  // use repository here

  // rollback on exception, only commit when reach this last line:
  TransactionService.Commit();
}

      

You just get IDisposable, you don't need to know the session.



Repositories receive APIs for session access. For instance:

// example repository implementation
public Entity Get(Guid id)
{
  return SessionProvider.Session.Get<Entity>(id);
}

      

To accomplish this, I put the session in a variable ThreadStatic

that is initialized to CreateTransaction

and returned SessionProvider.Session

.

+1


a source


Take a look at the S # arp architecture . It answers everything you need, including how to separate the data tier (NHibernate), web tier, and business logic.



+1


a source


0


a source







All Articles