0 day streak
csharp / expert
Snippet

Middleware Pattern for Modular Request Flows

Modern framework architectures use a 'Chain of Responsibility' implemented via delegates. This snippet demonstrates how to build a modular pipeline where each component can process a request and decide whether to call the 'next' delegate.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public delegate Task RequestDelegate(HttpContext context);
public class MiddlewarePipeline {
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
delegate Task RequestDelegate
Defines a functional contract for processing an operation asynchronously.
2
app = _components[i](app)
Wraps the existing pipeline in the new middleware component, creating a nested onion-style execution.