How to use factory-based middleware activation in ASP.NET Core


When you create an ASP.NET Core application, you can draw on various middleware components to monitor, manage, or modify the requests and responses that flow through the pipeline. You can too list your middleware in ASP.NET Core.

In general, you have tools in the middle of the application pipeline in ASP.NET Core. In this article, we’ll look at the basics in ASP.NET Core and how to work with convention-based methods and factories.

To use the code samples provided in this article, you must have Visual Studio 2022 installed on your computer. If you haven’t already, you can Download Visual Studio 2022 here.

Create an ASP.NET Core 7 Web API project in Visual Studio 2022

First, let’s create an ASP.NET Core 7 project in Visual Studio 2022. Follow these steps:

  1. Start the Visual Studio 2022 IDE.
  2. Click on “Create a new project.”
  3. In the “Create a new project” window, select “ASP.NET Core Web API” from the list of icons displayed.
  4. Click Next.
  5. In the “Edit your new project” window, specify a name and location for the new project.
  6. Check the box “Place method and project in the same directory”, depending on your preference.
  7. Click Next.
  8. In the “Additional Features” window that is shown next, uncheck the box “Use control services (do not check to use limited APIs)” We do not use limited APIs in this project. Leave the “Authentication Type” set to “None” (default).
  9. Make sure that the “Enable Open API Support,” “Enable HTTPS,” and “Enable Docker” boxes remain unchecked as we do not use these options here.
  10. Click Create.

We will use the ASP.NET Core 7 Web API project to work with the middleware factory in the steps below.

Understanding middleware in ASP.NET Core

Middleware is the software component that contains the request/response pipeline in ASP.NET Core. Incoming requests pass through each section of the pipeline, and each of the sections can either process the request or send it to another section of the pipeline.

There are many things that middleware can do, including authentication, authorization, logging, exception handling, routing, caching, and response compression. You can modify the functionality of your application in individual sections by adding, removing, or reconfiguring core components to suit your application’s needs and responses.

Traditionally, you have to configure your middleware components using the UseMiddleware extension method in the Start class or the Program.cs file when using the new ASP.NET Core. In contrast, factory-centered activation allows you to define and modify central devices using factories, which provides greater flexibility in activation.

Note that if you do not write your own middleware factory class, the default middleware factory will be used. In ASP.NET Core, you can initialize your middleware in two different ways: assembly-centered initialization and factory-centered initialization. Let’s now look at both ways.

The content of the ASP.NET Core core assembly

Open middleware in ASP.NET Core is a feature that allows you to use middleware in the request/response process based on predefined parameters, rather than explicitly modifying each middleware. The following list shows how to create the middle section.

public class ConventionalMiddleware
    {
        private readonly RequestDelegate _next;
        public ConventionalMiddleware(RequestDelegate next)
            => _next = next;
        public async Task InvokeAsync(HttpContext context)
        {
            Trace.WriteLine("Inside the Conventional Middleware.");
            await _next(context);
        }
    }

You can add this to the request pipeline using a code snippet in the Program.cs file.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<ConventionalMiddleware>();
app.Run();

Central to the factory in ASP.NET Core

The middleware factory in ASP.NET Core provides a flexible and powerful way to configure and initialize middleware. Using the middleware activation factory, you can customize the middleware settings based on the needs of your application.

Factory-built middleware allows you to install lifetime dependencies using the constructors of your middleware class – something that is not supported by the middleware program. Maximum lifetime means that the service is created once per client request, and discarded at the end of the request.

Industrial equipment has the following advantages over traditional or centralized equipment:

  • While the default assembly resources are created once during the initialization of an ASP.NET Core application, the default factory is created with each request.
  • Because the built-in software provides a service that can be enabled on a per-request basis, you can install scoped services in the middleware architecture.
  • The factory center tools encourage strong writing of the center type.

To use the middleware activation factory, you need to follow the four steps described below.

  1. Create a class that represents your middleware component and set the IMiddleware interface.
  2. Use the InvokeAsync method in your middleware that defines the middleware logic.
  3. Add content to a DI container using the AddSingleton or AddScoped method.
  4. Configure the middleware pipeline using the UseMiddleware extension method and specify the type of your middleware.

The following list shows how to write the middle part of the factory.

    public class FactoryActivatedMiddleware : IMiddleware
    {
        public async Task InvokeAsync(HttpContext context,
        RequestDelegate next)
        {
            Trace.WriteLine("Inside the Factory Activated Middleware.");
            await next.Invoke(context);
        }
    }

You must register the middleware in the service container using the following snippet.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<FactoryActivatedMiddleware>();

Now you can add this middleware just like we added middleware in the assembly middleware example.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<FactoryActivatedMiddleware>();
app.Run();

Each call to the UseMiddleware extension method checks whether the middleware implementation of the query matches the IMiddleware interface. When this is achieved, the IMiddlewareFactory instance registered in the service container is used to resolve the implementation of the IMiddleware interface instead of the implementation between the assemblies. This middleware is registered as a temporary or virtual service within the service container.

The IMiddlewareFactory interface defines two methods, namely the Create(Type) and Release(IMiddleware) methods. While the Create(Type) method is used to create the middleware instance for each request, the Release(IMiddleware) method releases the IMiddleware instance at the end of the request. The default implementation of IMiddlewareFactory is available in the Microsoft.AspNetCore.Http.MiddlewareFactory class.

Copyright © 2023 IDG Communications, Inc.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *