开发者

How to handle NHibernate sessions in an ASP.NET WebForms application?

I see there are 2 possible scenarios as to the session handling:

  1. Open one single ISession per request. Open it at request start and close it at request end.
  2. Open one ISession per conceptual "unit of work". Many sessions are created for a request.

The approach #1 is the one I'm doing now. I'm a little bit worried about it because, although it works, it's a little bit difficult to debug. For instance, I have an object not being saved (even though I ordered it开发者_运维问答 to) and I'm having trouble debugging since there's a LOT of things happening during a complete request life-cycle.

The approach #2 seems to be the standard best-practice (not sure about ASP.NET) and I'm sure it's pretty easier to debug. The problem I see is about inter-session communication. For instance: My Page class holds a reference to the User, which is a persistent object. Many of the operations receive the user as parameter. As the user belongs to a different session, I can't pass it as a parameter.

I'm biased to #2, but I don't know if it's the best practice, nor how to deal with cross-session object.

Thanks.


Most people do Session-Per-Request for the reasons you outline and for simplicity.

However, you can open and commit transactions for each "unit of work". So you will have many transactions for each session. (It is also usual practice to make sure that when the transaction is committed, the session is flushed at the same time).

For example, after clicking the save button, open and commit a transaction.

The session will take care of keeping track of all your entities. The transaction will take care of flushing to the database when necessary.

With this setup it should be easier to debug your problem.


For the ASP.NET project I'm working on now, I use a combination of these approaches.

I open an ISession at the beginning of a request and close it at the end of the request, as you do with your first approach, and I use the session to load any entities that need to remain attached to a session for the duration of the request.

However, when I need to save or update or delete an entity, I create a new transient object and hand it to a new ISession, separate from the one tied to the request. For additional units of work, I create additional sessions.


You may find NHibernate Burrow helpful, or at least interesting in this regard, as it is designed to assist with session management in ASP .NET applications, implementing the concept of a "long-running conversation" that spans multiple requests.


I think your real question is why cant I get my objects to save.

Even thought you are using a single ISession you still need to either Flush the session or commit transaction for some Save/Update/Delete actions to be commited.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜