Class BackgroundExecutionMiddleware
Middleware that detects and executes messages marked for background processing.
public sealed class BackgroundExecutionMiddleware : IDispatchMiddleware
- Inheritance
-
BackgroundExecutionMiddleware
- Implements
- Inherited Members
- Extension Methods
Remarks
This middleware intercepts messages implementing IExecuteInBackground and hands them to a background worker, returning immediately with a successful result whose Disposition is AcceptedForBackgroundExecution. That disposition is the contract: the dispatch succeeded and the handler has not run, so a caller recording completion must not treat it as done. Messages expecting typed results cannot be executed in the background and fail with a 400 Bad Request error.
A dispatch whose token is already cancelled is not accepted: the handler never runs and the result is Cancelled(). Once accepted, the work no longer follows the caller's token — that token is often request-scoped and fires when the response carrying the acceptance completes. It runs until it finishes, and is cancelled only when the host's shutdown budget elapses with it still running.
A failing background message is always logged. What happens next is the host-level policy ExceptionBehavior.
Constructors
BackgroundExecutionMiddleware(IOptions<BackgroundExecutionOptions>, ILogger<BackgroundExecutionMiddleware>, IHostApplicationLifetime?)
Initializes a new instance of the BackgroundExecutionMiddleware class.
public BackgroundExecutionMiddleware(IOptions<BackgroundExecutionOptions> options, ILogger<BackgroundExecutionMiddleware> logger, IHostApplicationLifetime? hostApplicationLifetime = null)
Parameters
optionsIOptions<BackgroundExecutionOptions>The background execution options.
loggerILogger<BackgroundExecutionMiddleware>Logger for diagnostic information.
hostApplicationLifetimeIHostApplicationLifetimeThe host's lifetime. Required when ExceptionBehavior is StopHost.
Exceptions
- InvalidOperationException
StopHost is configured and no
hostApplicationLifetimeis supplied.
Properties
Stage
Gets the pipeline stage where this middleware should execute.
public DispatchMiddlewareStage? Stage { get; }
Property Value
- DispatchMiddlewareStage?
The current Stage value.
Remarks
Executes near the end of the pipeline to ensure validation and authorization have already been performed.
Methods
InvokeAsync(IDispatchMessage, IMessageContext, DispatchRequestDelegate, CancellationToken)
Processes messages marked for background execution.
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "Background execution checks only known dispatch message types registered at startup.")]
public ValueTask<IMessageResult> InvokeAsync(IDispatchMessage message, IMessageContext context, DispatchRequestDelegate nextDelegate, CancellationToken cancellationToken)
Parameters
messageIDispatchMessageThe message being processed.
contextIMessageContextThe message context.
nextDelegateDispatchRequestDelegateThe next middleware in the pipeline.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
- ValueTask<IMessageResult>
For a background message, a completed task carrying a successful result whose Disposition is AcceptedForBackgroundExecution -- the work is accepted and pending, not complete. For any other message, delegates to the next middleware.
Exceptions
- ArgumentNullException
Thrown when required parameters are null.