Codebelt
Illustration of a Request/Response pipeline with a middleware component in the middle.

ASP.NET Core: Middleware by Abstraction

Cuemon.AspNetCore adds typed base classes for convention-based middleware, with request-time dependencies and optional configuration through IOptions or an Action delegate.

LIBRARIES
  • Cuemon
  • ASP.NET Core
  • Middleware
  • Dependency Injection
  • Options Pattern
Parallel pipes illustrating an HTTP middleware pipeline.

ASP.NET Core supports convention-based middleware and factory-based middleware using IMiddleware and IMiddlewareFactory. Both are useful, supported approaches. Cuemon adds base classes to the convention-based approach so the invocation signature and configuration contract are explicit in the type hierarchy.

Note

Originally published on the Cuemon blog at 22:41 UTC on 30 September 2018. The publication timestamp and original image are retained; API names and examples have been updated for Cuemon 11.0.0. The old blog displayed the date as 1 October; this edition uses the recorded UTC timestamp.

Compare with the original Cuemon blog version, captured 14 November 2026: Read archived webpage. The archive includes later edits made on the original blog; historical links are inactive.

The examples use Cuemon.AspNetCore. The ready-made registration extensions shown below come from Cuemon.Extensions.AspNetCore:

dotnet add package Cuemon.AspNetCore --version 11.0.0
dotnet add package Cuemon.Extensions.AspNetCore --version 11.0.0

Start with the ASP.NET Core conventions

A conventional component receives the next RequestDelegate in its constructor and exposes a public Invoke or InvokeAsync method. A minimal pass-through implementation looks like this:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace MiddlewareExamples;

public sealed class ConventionalMiddleware
{
    private readonly RequestDelegate _next;

    public ConventionalMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task InvokeAsync(HttpContext context)
    {
        return _next(context);
    }
}

Factory-based middleware instead implements InvokeAsync(HttpContext, RequestDelegate) from IMiddleware and is registered as a scoped or transient service. ASP.NET Core resolves that component per request, allowing scoped constructor dependencies.

Cuemon's base classes keep convention-based activation. Inheriting from them does not turn a component into factory-activated middleware.

Middleware with zero to five request-time dependencies

Middleware supplies the protected Next delegate and requires an InvokeAsync(HttpContext) override. Generic variants support one through five additional parameters resolved by ASP.NET Core for each request.

Here is an implementation with one dependency, IHostEnvironment:

using System.Threading.Tasks;
using Cuemon.AspNetCore;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

namespace MiddlewareExamples;

public sealed class EnvironmentItemMiddleware : Middleware<IHostEnvironment>
{
    public EnvironmentItemMiddleware(RequestDelegate next) : base(next)
    {
    }

    public override Task InvokeAsync(HttpContext context, IHostEnvironment environment)
    {
        context.Items["HostingEnvironment"] = environment.EnvironmentName;
        return Next(context);
    }
}

Register it with app.UseMiddleware<EnvironmentItemMiddleware>() before components that read the item. The host already registers IHostEnvironment; application-specific dependencies must be registered separately.

Request-scoped services belong in the invocation method when using conventional activation. The generic signature makes those dependencies visible without adding a constructor field for each one.

ConfigurableMiddleware and the options pattern

ConfigurableMiddleware<TOptions> adds configuration. Its generic variants place request-time dependencies first and TOptions last. The options type must be a class implementing IParameterObject and have a public parameterless constructor. An IValidatableParameterObject can also provide configuration validation.

The base supports constructors accepting either IOptions<TOptions> or Action<TOptions>. Derived implementations expose the constructors they support and read configuration through the inherited Options property.

Cuemon's own HostingEnvironmentMiddleware is a concrete example. It derives from ConfigurableMiddleware<IHostEnvironment, HostingEnvironmentOptions> and registers an OnStarting callback to add the configured environment header before the response starts.

To use the existing implementation, call its extension method:

using Cuemon.Extensions.AspNetCore.Hosting;

// After builder.Build(), before the endpoints execute:
app.UseHostingEnvironment(options =>
{
    options.HeaderName = "X-Hosting-Environment";
});

The default suppression predicate omits the header in Production. The earlier IHostingEnvironment interface has been replaced here by IHostEnvironment, and the current extension is UseHostingEnvironment, rather than UseHostingEnvironmentHeader.

Register a configurable component consistently

When writing an extension for a custom configurable component, use Cuemon.AspNetCore.Builder.MiddlewareBuilderFactory.UseConfigurableMiddleware<TMiddleware, TOptions>.

The factory selects the options-based activation path when no setup delegate is supplied. When a delegate is supplied, it validates the configuration and passes the delegate into middleware activation. The middleware must expose the corresponding public constructor. This is the current replacement for the original article's ApplicationBuilderFactory.UseMiddlewareConfigurable call.

For the built-in environment middleware, the equivalent direct registration is:

using Cuemon.AspNetCore.Builder;
using Cuemon.AspNetCore.Hosting;

MiddlewareBuilderFactory.UseConfigurableMiddleware<HostingEnvironmentMiddleware, HostingEnvironmentOptions>(
    app,
    options => options.HeaderName = "X-Hosting-Environment");

Use this instead of the earlier app.UseHostingEnvironment(...) call, rather than registering the same component twice.

The benefit is a small shared contract: Next for pipeline continuation, explicit request-time dependencies, and Options for configuration. Standard ASP.NET Core activation and service lifetimes still apply.

Code with passion.

Timeline

The stable releases below show how the middleware abstractions retained their activation model while registration names, options constraints, and defaults changed. The earliest snapshot confirms an existing implementation, rather than its first-ever origin.

  1. v5.1.2019 2019-02-09

    Configurable middleware already supported both options forms.

    The tagged ConfigurableMiddleware<TOptions> exposes constructors for IOptions<TOptions> and Action<TOptions>. Registration uses the earlier ApplicationBuilderFactory.UseMiddlewareConfigurable names found in the original article.

  2. v6.0.0 2021-04-18

    The registration factory acquired its current names.

    ApplicationBuilderFactory became MiddlewareBuilderFactory, and the configurable registration method became UseConfigurableMiddleware. The options-based and delegate-based activation paths continued behind that renamed surface.

  3. v7.0.0 2022-11-09

    Middleware options gained an explicit parameter-object constraint.

    Configurable middleware now requires TOptions to implement IParameterObject, alongside the existing class and parameterless-constructor constraints. This makes the configuration contract part of the generic API.

  4. v8.1.0 2024-02-11

    Registration validated setup delegates, and environment headers were suppressed in Production.

    The factory added validation before passing a supplied configuration delegate into middleware activation. The same release changed HostingEnvironmentOptions so its default suppression predicate excludes Production.

  5. v11.0.0 2026-11-11 (current)

    The abstractions remain in Cuemon.AspNetCore with IHostEnvironment integration.

    The current stable HostingEnvironmentMiddleware derives from ConfigurableMiddleware<IHostEnvironment, HostingEnvironmentOptions>. MiddlewareBuilderFactory retains the configurable registration surface described above; the ready-made UseHostingEnvironment extension belongs to Cuemon.Extensions.AspNetCore.

Sources