Skip to content

CoreMemoryCache complex key structure causes LazyInitializationException "Could not initialize proxy - no Session" #170

@FS-FrankLakmann

Description

@FS-FrankLakmann

Hello,

I was chasing a very odd LazyInitializationException error in our code when doing something repeatedly. It seemed to come from inside the SLC usage. After some debugging I found out, that a proxy instance from a previous service call (it's session is long gone) was accessed to do some Equals comparison. Where did it get reused? Who holds that state? It's the SLC itself inside the CacheKey.

The object structure is a bit special:
The root is of EntityType X (actually WflElementEntity in the screenshot below), that has a HasMany with LazyLoad . Y represents a m:n mapping table between X and Z (actually EventTemplateEntity). The mapping of Y uses a compositeId with key references to X and Z. All 3 are secondlevel cached.

When debugging inside the CoreMemoryCacheBase and deeper inside the TryGetValue of the MemoryCache, there is a component of the key that is a NHibernate proxy instance for Entity Z. The exception happens in the comparer.Equals

Image

and this is how the key looks (Z from above is EventTemplateEntity)

Image

This means the keys of the SLC hold state that should not be held. I would consider that a conceptional bug. To me the reason seems obvious and also the solution:
CoreMemoryCacheBase.GetCacheKey keeps the potentially complex key structure and uses it as it is.

With the old framework 4 we have been using SysCache2 with no problems for years. It's GetCacheKey method simplifies the key into a primitive type string which prevents the issue of held state completely. RtMemoryCache also does that and in my short test that works fine in dotnet 8.

The problem is: We have a bit of time pressure to ship our dotnet8 version. Should we use RtMemoryCache? How risky is that switch?
Or should we "patch" the CoreMemoryCacheBase.GetCacheKey to behave like the other two? Please consider that as a long therm solution to this issue.

Thank you in advance
Frank

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions