Class-based middleware

Middleware can also be implemented by using a class-based approach. This kind of approach increases the reusability, testability, and maintainability of middleware. A class-based approach involves the definition of a new type, for example. Let's have a look at class-based middleware:

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

namespace Demo.WebAPI
{
public class SampleMiddleware
{
private readonly RequestDelegate _next;

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

public async Task InvokeAsync(HttpContext context)
{
//DO STUFF

// Call the next delegate/middleware in the pipeline
await _next(context);
}
}
}

Let's examine some key points in this class:

  • RequestDelegate represents the reference to the next element in the pipeline. This could be a delegate or other class-based middleware.
  • InvokeAsync is the core part of our middlewareThis contains the implementation of the middleware and calls the _next element in our pipeline. At this point, our implementation must choose between continuing the pipeline or only returning a result to the client. For example, in the case of a not authorized message, the middleware will interrupt the pipeline.

After defining our middleware class, we need to add it to our pipeline. An excellent way to do this is to establish a new extension method as follows:

public static class SampleMiddlewareExtensions
{
public static IApplicationBuilder UseSampleMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<SampleMiddleware>();
}
}

After this, we can add our middleware to the pipeline in our Startup class by executing the extension method previously defined:


public class Startup
{

// ...

public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseSampleMiddleware();

app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});
}
}

The preceding implementation provides a way to encapsulate the logic of the middleware in the SampleMiddleware class. This approach is preferred for various reasons. First of all, the middleware class and the logic can be verified and tested using unit tests. Secondly, in an enterprise environment, it can be useful to create dedicated library projects containing common middleware used by the web services and to distribute them through the company's NuGet repository. Finally, the class-based approach provides a clear way to highlight middleware dependencies using constructor injection. We will look at this topic in more depth in Chapter 4, Dependency Injection. Now that we have seen how to declare and add middleware to the ASP.NET Core pipeline, it is necessary to cover the conditional initialization of middleware in slightly more depth.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.13.255