0 day streak
csharp / intermediate
Snippet

Building a Custom Middleware Pipeline

Middleware patterns allow you to chain behaviors around a core logic. This implementation uses delegates and higher-order functions to wrap a handler, a common architectural pattern found in modern web engines but implemented here in pure C#.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public delegate void WorkHandler(string context);
public class PipelineBuilder
{
public WorkHandler Build(List<Func<WorkHandler, WorkHandler>> middlewares)
{
WorkHandler pipeline = (ctx) => Console.WriteLine("Final Target: " + ctx);
for (int i = middlewares.Count - 1; i >= 0; i--)
{
pipeline = middlewares[i](pipeline);
}
return pipeline;
}
}
Breakdown
1
public delegate void WorkHandler(string context);
Defines the signature for the functions that will process the context.
2
pipeline = middlewares[i](pipeline);
Wraps the current pipeline with the next middleware in the list.