Passing Parameters to Middleware in ASP.NET Core 2.0

Problem

How do you pass parameters to middleware during its setup in ASP.NET Core.

Solution

In an empty project add a POCO class to hold parameters for the middleware:

Add a middleware:

Solution A: Instance Type

Add extension method to configure the middleware:

Configure the middleware:

Solution B: Function Type

Add extension method to configure the middleware:

Configure the middleware:

Discussion

I discussed in an earlier post that it is good practice to defined middleware in a separate class and add to the pipeline using extension methods. We may also need to pass information to our middleware classes though and Iā€™ve come across two patterns for this when digging into ASP.NET Core source code and other samples online.

These are really straight forward as demonstrated in solution A and B above. We wrap our parameters in a POCO class and create an extension method that takes in either:

  1. POCO instance
  2. Function to call, which in turn sets up the POCO.

Note: that the POCO is passed on to the middleware in its constructor. UseMiddleware() method takes in params object[] for arguments to be passed onto middleware constructor.

Configuring Services

These patterns could also be used for setting up dependency injection the service container. To demonstrate add a service:

Add either of these extension methods to configure services:

Configure services with either of these:

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Asp.Middleware.Options

Leave a Reply