concept middleware in category .net

This is an excerpt from Manning's book Microservices in .NET Core: with examples in Nancy.
Figure 1.10. An OWIN web server with OWIN middleware and an OWIN web application on top. The web server delegates incoming requests to the layers above: in this case, the request-logging middleware, which writes a log message about the request and then delegates to the web application. To the web server, the middleware looks like an OWIN-compliant application; and to the application, the middleware looks like an OWIN-compliant web server.
![]()
In figure 1.10, the stack includes only one piece of middleware, but there’s no reason you couldn’t have more. One piece of middleware can delegate to another piece of middleware as well as to an application. As long as all the pieces use the OWIN interface, you can compose the stack with as many pieces of middleware as you like.
Nancy is OWIN-compliant, so the microservices you build with Nancy work as OWIN applications in the OWIN pipeline. In this book, you’ll use middleware to take care of a number of cross-cutting technical concerns that don’t fit nicely with application code. In part 3, we’ll dive into implementing support for monitoring, performance logging, request logging, and security as pieces of middleware that can be reused across all your microservices.
You can gain two primary benefits from using middleware: cross-cutting technical concerns are separated nicely from the application logic, and the middleware can be reused so you can easily build new microservices without having to spend time rebuilding the same monitoring, logging, and security code.
Writing middleware as lambda functions works, but it becomes somewhat difficult when the middleware is more complex. In such cases, it’s nicer to use a class to implement the middleware.
To use a class to implement middleware, you can create a class that has a method whose signature is the AppFunc.
Middleware in this style takes in the nextAppFunc in the constructor and stores it in a private variable, such that it can be called as needed in the Invoke method, which implements the middleware’s behavior. To add this kind of middleware to the OWIN pipeline, you instantiate it and then use the Invoke method as a delegate:
app.UseOwin(buildFunc => buildFunc(next => new ConsoleMiddleware(next).Invoke));Now you know how to implement middleware as lambdas as well as classes. Next, let’s look at testing middleware.
As a lambda— You’ve seen middleware as a lambda in chapter 1 as well as earlier in this chapter. In the next section, I’ll reiterate this style.