AspNetCore.Docs/aspnetcore/fundamentals/middleware/extensibility-third-party-c...

4.1 KiB

title author description ms.author manager ms.custom ms.date ms.topic ms.technology ms.prod uid
Factory-based middleware activation with a third-party container in ASP.NET Core guardrex Learn how to use strongly-typed middleware with factory-based activation and a third-party container in ASP.NET Core. riande wpickett mvc 02/02/2018 article aspnet asp.net-core fundamentals/middleware/extensibility-third-party-container

Factory-based middleware activation with a third-party container in ASP.NET Core

By Luke Latham

This article demonstrates how to use IMiddlewareFactory and IMiddleware as an extensibility point for middleware activation with a third-party container. For introductory information on IMiddlewareFactory and IMiddleware, see the Factory-based middleware activation topic.

View or download sample code (how to download)

The sample app demonstrates middleware activation by an IMiddlewareFactory implementation, SimpleInjectorMiddlewareFactory. The sample uses the Simple Injector dependency injection (DI) container.

The sample's middleware implementation records the value provided by a query string parameter (key). The middleware uses an injected database context (a scoped service) to record the query string value in an in-memory database.

[!NOTE] The sample app uses Simple Injector purely for demonstration purposes. Use of Simple Injector isn't an endorsement. Middleware activation approaches described in the Simple Injector documentation and GitHub issues are recommended by the maintainers of Simple Injector. For more information, see the Simple Injector documentation and Simple Injector GitHub repository.

IMiddlewareFactory

IMiddlewareFactory provides methods to create middleware.

In the sample app, a middleware factory is implemented to create an SimpleInjectorActivatedMiddleware instance. The middleware factory uses the Simple Injector container to resolve the middleware:

[!code-csharp]

IMiddleware

IMiddleware defines middleware for the app's request pipeline.

Middleware activated by an IMiddlewareFactory implementation (Middleware/SimpleInjectorActivatedMiddleware.cs):

[!code-csharp]

An extension is created for the middleware (Middleware/MiddlewareExtensions.cs):

[!code-csharp]

Startup.ConfigureServices must perform several tasks:

  • Set up the Simple Injector container.
  • Register the factory and middleware.
  • Make the app's database context available from the Simple Injector container for a Razor Page.

[!code-csharp]

The middleware is registered in the request processing pipeline in Startup.Configure:

[!code-csharp]

Additional resources