I'm creating a chain of responsibility pipeline using System.Func<T, T>
where each function in the pipeline holds a reference to the next.
When building the pipeline, I'm unable to pass the inner function by reference as it throws a StackOverflowException due to the 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"); // StackOverFlowException
I can work around this with a closure:
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 build up this chain of functions, perhaps using Expressions?