0 day streak
csharp / expert
Snippet

Building a Custom Middleware Pipeline Logic

Framework-like architectures are often built on the Chain of Responsibility pattern. This snippet demonstrates how to manually construct a middleware pipeline using higher-order functions. Each 'Use' call wraps the next component, allowing for pre- and post-processing logic without external libraries.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public delegate Task RequestDelegate(string context);
public class PipelineBuilder
{
private readonly List<Func<RequestDelegate, RequestDelegate>> _components = new();
public void Use(Func<RequestDelegate, RequestDelegate> middleware)
{
_components.Add(middleware);
}
public RequestDelegate Build()
{
RequestDelegate app = (context) => Task.CompletedTask;
for (int i = _components.Count - 1; i >= 0; i--)
{
app = _components[i](app);
}
return app;
}
}
Breakdown
1
public delegate Task RequestDelegate(string context)
The core abstraction representing an asynchronous operation in the pipeline.
2
app = _components[i](app)
Recursively wraps delegates to create a nested execution chain (functional composition).