How to keep long running NHibernate Session data c

2019-04-11 16:03发布

I have NHibernate sessions cached in the ASP.NET session.

I came across a situation where a user edited an object so it's in their first level cache in the ISession. Another user then edited the same object.

At this point User1 still sees their original version of their edits where as User2 sees the correct state of the object?

What is the correct way to handle this without manually calling session.Refresh(myObj) explicitly for every single object all the time?

I also have a 2nd level cache enabled. For NHibernate Long Session should I just disable the first level cache entirely?

Edit: Adding some more terminology to what I'm looking to achieve from 10.4.1. Long session with automatic versioning the end of this section concludes with

As the ISession is also the (mandatory) first-level cache and contains all loaded objects, we can propably use this strategy only for a few request/response cycles. This is indeed recommended, as the ISession will soon also have stale data.

I'm not sure what kind of documentation this is for it to include both probably and then immediately say the session will have stale data (which is what I'm seeing). What's the solution to this right here or is there none?

3条回答
Juvenile、少年°
2楼-- · 2019-04-11 16:39

Apparently this is a known shortcoming of NHibernate as detailed by documentation cited in my question.

查看更多
家丑人穷心不美
3楼-- · 2019-04-11 16:44
查看更多
▲ chillily
4楼-- · 2019-04-11 16:51

Just use IStatelessSession instead of ISession.

Also keep in mind that NH wasn't designed to be used with long-living ISessions (as already mentioned by others). One problem is that you already mentioned. The other is that the performance drops significantly when there's a large object graph tracked by NH. Both problems could be avoided by using IStatelesSession. It gives you detached objects not being tracked by NH.

Not sure about the reasoning behind keeping sessions in the ASP.NET session. Maybe you could provide some details?

Also remember that a session is a wrapper over IDbConnection. Keeping it open can easily lead to conneciton pool starvation.

查看更多
登录 后发表回答