I'm writing a custom middleware for ASP.NET Core 2.2. According to Microsoft Docs on writing custom middlewares:
Middleware components can resolve their dependencies from dependency injection (DI) through constructor parameters.
UseMiddleware<T>
can also accept additional parameters directly.
This seems all good, but it doesn't say what happens when I mix the two ways, e.g. use DI and pass parameters in UseMiddleware<T>
. For example, I have the following middleware:
public class CustomMiddleware
{
public CustomMiddleware(RequestDelegate next, ILogger<CustomMiddleware> logger, CustomMiddlewareOptions options)
{
...
}
public async Task InvokeAsync(HttpContext context)
{
...
}
where logger
is provided by DI and options
is provided like the following:
app.UseMiddleware<CustomMiddleware>(new CustomMiddlewareOptions());
My own testing with 2.2 seems to show that this works fine, and the order of the parameters in the constructor doesn't matter (I can place DI parameter before or after manually-passed parameter, or even in between two manually-passed parameters). But I'm looking for some assurances that what I'm doing is OK. It would be really great if anyone could point to some docs or source code that supports this sort of usage. Thanks!