Tom Bushell
Tom Bushell

Reputation: 5875

Can I derive from IBindingList to facilitate lazy loading in NHibernate?

I'm using a class derived from IBindingList to databind a 3rd party WinForms grid to a database via NHibernate, using lazy loading.

Currently, to make lazy loading work, I need to keep an NH session open all the time, so that when the user clicks on a new row in the grid, there's a session available to load the rest of the object graph for the object selected.

However, many people suggest that this is bad practice.

So, I'm wondering if I can hook into IBindingList somehow to intercept data fetches originating from the grid, and create and discard sessions on the fly.

I quickly looked at IBindingList in the Object Browser, and the only thing that looked plausible was to override the indexer ("this [int]") in IList< T >.

Is this a viable approach, or is there a better way?

Upvotes: 0

Views: 232

Answers (1)

Felice Pollano
Felice Pollano

Reputation: 33262

In order to me the one you proposed is the best approach. I used it in past, and I suggest to decida a "page" size, and load in the indexer an entire page if not yet cached. Use SetMinResult, SetMaxResults to fech pages of records, and keep an undelyng dictionary of page already present. Some little hack to remember: delete all the item cached when you change sort/filters. I wrote a post about my solution here:

http://www.felicepollano.com/Trackback.aspx?guid=831f463b-f3cf-47e4-b210-b80f6c6d1b32 that is not perfect but working ;). Some more example you can find ( I think ) in the unofficial NHibernate addins.

Upvotes: 1

Related Questions