在閱讀本文章以前,你能夠先閱讀:異步
.NET中的簡單中介者模式實現,一種進程內消息傳遞機制(無其餘外部依賴)。 支持以同步或異步的形式進行請求/響應,命令,查詢,通知和事件的消息傳遞,並經過C#泛型支持消息的智能調度。async
MediatR能夠支持幾種模式:請求/響應模式與發佈模式。this
請求/響應模式,也能夠叫作命令模式,是一對一的消息傳遞,一個消息對應一個消息處理。spa
首先,將MediatR,MediatR.Extensions.Microsoft.DependencyInjection的NuGet軟件包安裝到您的應用程序中。code
MediatR MediatR.Extensions.Microsoft.DependencyInjection
而後,咱們經過Startup.ConfigureServices增長AddMediatR來註冊組件。orm
services.AddMediatR(typeof(TenantRequestHandler).Assembly);
接着,定義消息類。進程
namespace MediatR.WebApi { public class TenantRequest : IRequest<string> { public TenantRequest(string message) { Message = message; } public string Message { get; } } }
接着,定義消息處理類。事件
using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; namespace MediatR.WebApi { public class TenantRequestHandler : IRequestHandler<TenantRequest, string> { private readonly ILogger<TenantRequestHandler> logger; public TenantRequestHandler(ILogger<TenantRequestHandler> logger) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public Task<string> Handle(TenantRequest request, CancellationToken cancellationToken) { logger.LogInformation($"Handled: {request.Message}"); return Task.FromResult(request.Message); } } }
最後,建立HomeController,發佈請求get
using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace MediatR.WebApi.Controllers { [Route("[controller]")] [ApiController] public class HomeController : Controller { private readonly IMediator mediator; public HomeController(IMediator mediator) { this.mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); } [Route("Example01")] [HttpGet] public async Task<IActionResult> Example01() { await mediator.Send(new TenantRequest { Message= "通知房客信息" }); return Ok(); } } }
項目中跟蹤會輸出:同步
Handled: 通知房客信息
發佈模式,是一對多的消息傳遞,一個消息對應多個消息處理。
安裝及註冊組件後,首先,定義消息類。
namespace MediatR.WebApi { public class LandlordNotification : INotification { public LandlordNotification(string message) { Message = message; } public string Message { get; } } }
接着,定義消息處理類。
using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; namespace MediatR.WebApi { public class LandlordNotificationHandler : INotificationHandler<LandlordNotification> { private readonly ILogger<LandlordNotificationHandler> logger; public LandlordNotificationHandler(ILogger<LandlordNotificationHandler> logger) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public Task Handle(LandlordNotification notification, CancellationToken cancellationToken) { logger.LogInformation($"Handled: {notification.Message}"); return Task.CompletedTask; } } }
最後,在HomeController,增長髮布請求
[Route("Example02")] [HttpGet] public async Task<IActionResult> Example02() { await mediator.Publish(new LandlordNotification("通知房東信息")); return Ok(); }
項目中跟蹤會輸出:
Handled: 通知房東信息