NHibernate Linq Session Management

I am testing Linq for NHibernate 2.1 for use in an ASP.NET MVC application, and I am trying to figure out session management. As a first experiment, I am trying to modify the SportsStore application from the Pro ASP.NET MVC Framework . This sample application uses Linq for Sql, so I thought it would be a good exercise. I have NHibernate 2.1, database access and non-Linq queries are working fine.

In Linq to SQL, we can create an IQueryable object from a data context and a connection string that can be passed and used without worrying about maintaining any context. So, for example, the source code of the product repository reads something like:

public IQueryable<Product> Products { get { (new DataContext(_connectionString)).GetTable<Product>(); } 

and the application uses the returned IQueryable to populate product lists, retrieve product details, etc.

In NHibernate, Linq uses a data context in a similar way, but instead of a connection string, we provide a session object that should remain in scope while using IQueryable:

 IQueryable<Product> products = new SportsStoreContext(session).Products; 

So, I am wondering how I should manage this session without doing too much violence on the structure of the sample application. Ideally, I would like to get a solution that would allow me to replace Linq with Sql code using NHibernate Linq, making only local changes.

The NHibernate session implements IDisposable, and most NHibernate samples demonstrate session management using the {} construct, but this strategy does not work here. This topic discusses several different approaches, S # arp Architecture and HybridSessionBuilder . Does anyone use them to replace Linq with Sql using NHibernate Linq? Are there other methods that will work better?

** EDIT mausch has this right - a common way to get close to this - using httpmodule. NHibernate in Action describes two ways to do this: session-per-request (p334) and conversation session (p340). The latter allows you to reuse persistent instances for multiple HTTP requests. In addition to the mausch links provided, NHibernate in Action mentions NHibernate Burrow , ActiveRecord Lock, and Rhino Tools .

+4
source share
2 answers

An IMO in the simplest way would be to have an httpmodule that manages the session (template for session per request) and then uses dependency injection to provide ISession controllers.

This is pretty much the approach used by S # arp and others .

LINQ for NHibernate is based on the "standard" NHibernate, so all session management templates are still applied.

I do not have a book, although I do not know how much would need to be changed ...

+4
source

Rhino Commons is also a solution. I use it in an ASP.NET MVC application, it works fine.

0
source

All Articles