Aspnetcore.docs: Why use an extension method?

Created on 30 Jan 2020  Â·  3Comments  Â·  Source: dotnet/AspNetCore.Docs

Why not just call UseMiddleware<RequestCultureMiddleware>(); directly on the app?


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

P2 Source - Docs.ms doc-enhancement

Most helpful comment

Yeah, the extension method is just a wrapper around that call, so both options work. Using an extension method is a convention that's adopted by the built-in middleware components.

Consider a typical middleware pipeline setup that uses endpoint routing, authn, and authz:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(...);
````

Consider that same configuration without the extension methods:

```csharp
app.UseMiddleware<EndpointRoutingMiddleware>();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMiddleware<AuthorizationMiddleware>();
app.UseMiddleware<EndpointMiddleware>(...);

There's a lot of noise in that second example, especially around the repeated Middleware. An extension method also allows additional configuration and checks, too. Some of those Use extensions shown above do extra work, such as adding more configuration and verifying that services have been registered.

You certainly don't have to use an extension method, if you don't like the convention and don't have additional configuration needs, etc.

All 3 comments

@serpent5

Yeah, the extension method is just a wrapper around that call, so both options work. Using an extension method is a convention that's adopted by the built-in middleware components.

Consider a typical middleware pipeline setup that uses endpoint routing, authn, and authz:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(...);
````

Consider that same configuration without the extension methods:

```csharp
app.UseMiddleware<EndpointRoutingMiddleware>();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMiddleware<AuthorizationMiddleware>();
app.UseMiddleware<EndpointMiddleware>(...);

There's a lot of noise in that second example, especially around the repeated Middleware. An extension method also allows additional configuration and checks, too. Some of those Use extensions shown above do extra work, such as adding more configuration and verifying that services have been registered.

You certainly don't have to use an extension method, if you don't like the convention and don't have additional configuration needs, etc.

Good question and fantastic answer.

Was this page helpful?
0 / 5 - 0 ratings