ASP.NET Core Interview Question #99
What is IMiddleware and how is it different from conventional middleware?
Middleware & Request Pipeline Mid-Level Intermediate
Quick Interview Answer
IMiddleware provides a factory-activated middleware model. A class implements IMiddleware and is registered with the dependency injection container. The framework resolves it through IMiddlewareFactory when the pipeline executes it.
Detailed Explanation
IMiddleware provides a factory-activated middleware model. A class implements IMiddleware and is registered with the dependency injection container. The framework resolves it through IMiddlewareFactory when the pipeline executes it.
Because the middleware itself is DI-activated, constructor injection works naturally for services compatible with the middleware's registered lifetime.
Conventional middleware instead receives RequestDelegate in its constructor and commonly receives scoped dependencies through InvokeAsync parameters. IMiddleware is useful when full DI activation of the middleware class is desirable.
Code Example
public class AuditMiddleware : IMiddleware
{
private readonly IAuditService _auditService;
public AuditMiddleware(IAuditService auditService)
{
_auditService = auditService;
}
public async Task InvokeAsync(
HttpContext context,
RequestDelegate next)
{
await _auditService.RecordAsync(context.Request.Path);
await next(context);
}
}
builder.Services.AddScoped<AuditMiddleware>();
app.UseMiddleware<AuditMiddleware>();