An adaptation of the Mediator Library to be executed as a background service.
$ dotnet add package MediatR.BackgroundServiceThis library extends MediatR to enable the mediator pattern for background services in .NET applications. It uses a queue-based background task system, as described in the Microsoft Docs.
IBackgroundTaskQueue implementation.System.Threading.Channels for efficient, thread-safe task management.You can enqueue MediatR requests to be processed in the background from either a controller or another handler. Below are examples for both scenarios:
[ApiController]
[Route("api/[controller]")]
public class InitiateController : ControllerBase
{
private readonly IMediatRBackground _mediatorBackground;
// ... constructor omitted for brevity ...
[HttpPost("from-controller")]
public async Task<ActionResult> InitiateCall()
{
var request = new LongOperationRequest(Source: "Controller");
await _mediatorBackground.Send(request, default);
return Accepted("Action has been initiated. Check Logs for details...");
}
}
public class InitiateOperationHandler : IRequestHandler<InitiateOperationRequest, InitiateOperationResponse>
{
private readonly IMediatRBackground _mediatorBackground;
// ... constructor omitted for brevity ...
public async Task<InitiateOperationResponse> Handle(InitiateOperationRequest request, CancellationToken cancellationToken)
{
var backgroundRequest = new LongOperationRequest("Handler");
await _mediatorBackground.Send(backgroundRequest, default);
return new InitiateOperationResponse
{
Value = "Initiation from handler has been successful."
};
}
}
This approach allows you to offload long-running or resource-intensive operations to background processing, improving the responsiveness of your API endpoints.
MediatR is restricted to v12.5.0 in this library due to a licensing change in later versions. Please review the MediatR license if you plan to upgrade further.