This project is read-only.

NHibernate with Web Api

Topics: Web Api
Sep 19, 2011 at 11:35 AM

I'm trying to use the oData query elements that can be provided on in the request string of the URL in Web Api to control an NHibernate query and can see two options:

1. Obtain a copy of the query string data,  interpret it myself and add it to the IQueryable being generated for NHibernate, execute the query in a session then just return the result data from the service method.  This would allow me to set up and manage the NHibernate session before exiting the service method but this seems like a lot of work when clearly the Web Api has all the logic for parsing the query string and applying it to an IQueryable so I'd rather avoid doing that.

2. Set up the NHibernate IQueryable then return that from the method and let the Web Api add the additional magic to the IQueryable, execute the query get the results of the query then return them.  Actually, the seems to almost work, but there are problems with session management - the NHibernate session needs to be open after the service method has completed which means I can't control session management from there. (I've actually had some success if I open a session in the service method but just don't close it)

In a standard web app I would use a session-per-request approach and set up the session before and MVC action was executed and then dispose the session after the MVC action had completed - is there some way that I can do that using Web Api where it will execute the NHibernate session's disposal *after* the Web Api has executed the IQueryable returned from the service method?

Nov 21, 2011 at 4:13 PM

If you're using Castle Active Record with NHibernate then you would do this:

public void Application_BeginRequest(object sender, EventArgs e)
            HttpContext.Current.Items.Add("ar.sessionscope", new SessionScope());

        public void Application_EndRequest(object sender, EventArgs e)
                var scope = HttpContext.Current.Items["ar.sessionscope"] as SessionScope;
                if (scope != null)
            catch (Exception ex)
                HttpContext.Current.Trace.Warn("Error", "EndRequest: " + ex.Message, ex);
If you're not using Active Record then maybe it'll give you ideas of how to do the same with vanilla NHibernate.