I have been looking into lazy loading and its session requirements.
I've come up with a solution for loading lazy objects outside of a
standard SessionScope. All that was needed was a custom ByteCode
where the Initialize method was wrapped in a little session management
code.
The code is here:
http://gist.github.com/541691
The important bit is LazyInitializer.Initialize()
Unfortunately, this code requires that the original Initialize
function be virtual, which is not the case in the current release.
I added a request for this change to the NHibernate JIRA here:
http://216.121.112.228/browse/NH-2292
Hopefully it will not be too difficult to get this minor change
approved. If not, this strategy can still work by copying the entire
LazyInitializer implementation into the custom ByteCode.
I don't know too much about the internals of NH. I'm pretty much
poking at the dark with a stick here. This may not be bullet-proof,
but it works for the simple cases I have tried so far. I've done some
performance tests as well and this does not seem to degrade speed by
any appreciable amount.
This is only half the battle, however. It doesn't do anything for
lazy-load collections. That one is a bit more difficult, but a
similar strategy could be applied there as well. There are several
methods in AbstractPersistentCollection that would need to be
changed. And that class is the parent to a half dozen collection
classes.
I see two options. Either create a custom version of the entire
persistent collection infrastructure, or modify the current one to
inject the session verification strategy at run-time.
Creating a custom collection handler would be a pain in the ass, but
the current NH code already supports this. It looks like the ByteCode
provider can provide a custom CollectionTypeFactoryClass, though none
of them currently do.
Injecting the verification strategy would be much easier on my end.
But it would require a refactor of the entire collection proxy
complex. I don't know how easy it would be to get approved by the
guys over at NH.
Markus, or anyone else. Any comments or suggestions on this?