You're merging a set of Unit of work instances into another unit of work, but after commit? I don't see the purpose for the
this.InsertQueue.AddRange(uow.GetInsertQueue());
this.UpdateQueue.AddRange(uow.GetUpdateQueue());
lines.
The problem is that this copies objects from the queues, but when you commit the same UoW object again (I think you cache these? don't do that, never cache these objects, nor adapter, they're very lightweight, no need for caching) it creates new queues and therefore removes references to the old objects but as you copied them, they're still in memory!
So:
- don't cache adapters, unit of works etc. to avoid recreating them, they're lightweight and designed to be recreated every time.
- don't keep objects around like you do: the copy actions like the ones above keep objects in memory and the entities too. They might be attached to some object that ends up in the queue in a next uow commit, so all entities will be reexamined when the queues have to be calculated as it traverses the graph again (as they're all reachable).
- you can pass around a unit of work object: it doesn't know how to persist itself, that's by design. So instead of creating multiple unit of works and store them in a list, you can use 1 unit of work and pass that to methods that collect work: make these add their work to that unit of work, and simply commit that at the end.
As the error isn't deterministic, and occurs rarely, I think it's indeed a memory problem (not 'out of memory' but close, so you see all kind of weird things fail. It might be due to the copying of the data in the lines above (remove these at least). It's perhaps wise to monitor memory consumption over a week or 2 to see if you have a memory problem.