I create a chain of responsibility using System.Func<T, T> , where each function in the pipeline contains a link to the following.
When building a pipeline, I cannot pass an internal function by reference, because it throws a StackOverflowException due to a reassignment of the pipeline function, for example:
Func<string, Func<string, string>, string> handler1 = (s, next) => { s = s.ToUpper(); return next.Invoke(s); }; Func<string, string> pipeline = s => s; pipeline = s => handler1.Invoke(s, pipeline); pipeline.Invoke("hello");
I can get around this with closing:
Func<string, Func<string, string>, string> handler1 = (s, next) => { s = s.ToUpper(); return next.Invoke(s); }; Func<Func<string, string>, Func<string, string>> closure = next => s => handler1.Invoke(s, next); Func<string, string> pipeline = s => s; pipeline = closure.Invoke(pipeline); pipeline.Invoke("hello");
However, I would like to know if there is a more efficient way to create this chain of functions, possibly using expressions?
source share