Caching compiled expressions

Jun 18, 2009 at 2:30 PM


I'm using Flee to perform formatting of business objects and it does the job really nice. To avoid compiling the same expression multiple times, I cache the result of ExpressionContext.CompileDynamic.

Recently I have noticed, that I forgot to remove the expression owner (which in my case is a reference to some business object). As a result, affected business objects are not garbage collected. I failed setting IDynamicExpression.Owner to null, so I tried a different workaround (by replacing the expression owner with an instance of the same type that has no outgoing references).

But I don't feel comfortable with this and would like to ask, if there is a better way to cache the result of expression compilation without an expression owner or context?


(Let me know if the above lines are not clear enough - I am happy to share some lines of code...)

Jun 18, 2009 at 7:00 PM

You could use the clone method on an expression.  You create your source expression with an owner that has no outgoing references.  You then clone that expression and set its owner to a real version of the business object, evaluate, and let the cloned expression get garbage collected.

Cloning an expression skips the parsing and re-uses the compiled IL so it should be a fast operation.

The ideal solution would be to be able to set the owner to null but I have to do some thinking about the implications.

Jun 19, 2009 at 7:35 AM

Thanks for your quick reply and your suggestion! Although I am very interested in the ideal solution, I can live with the clone-workaround for the time being.