I have an MVC project that I exclusively employ a custom "Unit Of Work" pattern that uses NHibernate on the back end, which I expose to my application as IUnitOfWork and IUnitOfWorkFactory interfaces; These interfaces are injected as my NHibernate implementations via Ninject.
I use my UOW in a modified "session per request" style... I explicitly generate my IUnitOfWork from my injected IUnitOfWorkFactory when I need to perform database operations; it seems much easier to keep the CRUD where it belongs (out of my views and controllers) and effectively prevents accidental N+1 coding issues. Of course, it's a little harder to implement, but to date, I've been pretty happy with it.
Now I want to implement a WebAPI presenting IQueryable<Entity>-style REST calls, and my UOW pattern isn't digging it. The Queryables invariably blow up, attempting to invoke a disposed NHibernate session.
I've read some stuff online about how to implement a DelegatingHandler to manage the session for a WebAPI call... but I see several problems:
- It seems that all the examples are assuming a "Session per Request" pattern... which is by far the most popular pattern, but not exactly one which I am using, so I'm not sure that is even the proper direction to go.
- It's not clear how I can implement this handler exclusively for these Web API calls.
- I've seen a lot of suggestions to use a "Session per Conversation" pattern which is potentially even longer-lived than the "Session per Request" pattern... it sounds like it might be appropriate for this endeavor, but the documentation on how to implement it is a little sparse.
- All the sample implementations I've seen pretty much tightly couple the NHibernate
ISessionto the web application, using a built-in NHibernate mechanism (CurrentSessionContext.Bind(ISession)); I'd much rather reference myIUnitOfWorkinterface, and trust it to maintain the session it needs to.
So my question is, how can I implement a IQueryable<Entity> RESTful API using my own IUnitOfWork interface going against loosely-coupled NHibernate back-end?