使用.NET 6開發TodoList應用(9)——實現PUT請求
系列導航及源程式碼
需求
PUT
請求本身其實可說的並不多,過程也和創建基本類似。在這篇文章中,重點是填上之前文章里留的一個坑,我們曾經給TodoItem
定義過一個標記完成的領域事件:TodoItemCompletedEvent
,在SaveChangesAsync
方法里做了一個DispatchEvents
的操作。並且在DomainEventService
實現IDomainEventService
的Publish
方法中暫時以下面的程式碼代替了:
DomainEventService.cs
public async Task Publish(DomainEvent domainEvent)
{
// 在這裡暫時什麼都不做,到CQRS那一篇的時候再回來補充這裡的邏輯
_logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name);
}
在前幾篇應用MediatR
實現CQRS的過程中,我們主要是和IRequest/IRequestHandler
打的交道。那麼本文將會涉及到另外一對常用的介面:INotification/INotificationHandler
,來實現領域事件的處理。
目標
- 實現PUT請求;
- 實現領域事件的響應處理;
原理與思路
實現PUT
請求的原理和思路與實現POST
請求類似,就不展開了。關於實現領域事件響應的部分,我們需要實現INotification/INotificationHandler
介面,並改寫Publish
的實現,讓它能發布領域事件通知。
實現
PUT請求
我們拿更新TodoItem
的完成狀態來舉例,首先來自定義一個領域異常NotFoundException
,位於Application/Common/Exceptions
里:
NotFoundException.cs
namespace TodoList.Application.Common.Exceptions;
public class NotFoundException : Exception
{
public NotFoundException() : base() { }
public NotFoundException(string message) : base(message) { }
public NotFoundException(string message, Exception innerException) : base(message, innerException) { }
public NotFoundException(string name, object key) : base($"Entity \"{name}\" ({key}) was not found.") { }
}
創建對應的Command
:
UpdateTodoItemCommand.cs
using MediatR;
using TodoList.Application.Common.Exceptions;
using TodoList.Application.Common.Interfaces;
using TodoList.Domain.Entities;
namespace TodoList.Application.TodoItems.Commands.UpdateTodoItem;
public class UpdateTodoItemCommand : IRequest<TodoItem>
{
public Guid Id { get; set; }
public string? Title { get; set; }
public bool Done { get; set; }
}
public class UpdateTodoItemCommandHandler : IRequestHandler<UpdateTodoItemCommand, TodoItem>
{
private readonly IRepository<TodoItem> _repository;
public UpdateTodoItemCommandHandler(IRepository<TodoItem> repository)
{
_repository = repository;
}
public async Task<TodoItem> Handle(UpdateTodoItemCommand request, CancellationToken cancellationToken)
{
var entity = await _repository.GetAsync(request.Id);
if (entity == null)
{
throw new NotFoundException(nameof(TodoItem), request.Id);
}
entity.Title = request.Title ?? entity.Title;
entity.Done = request.Done;
await _repository.UpdateAsync(entity, cancellationToken);
return entity;
}
}
實現Controller:
TodoItemController.cs
[HttpPut("{id:Guid}")]
public async Task<ApiResponse<TodoItem>> Update(Guid id, [FromBody] UpdateTodoItemCommand command)
{
if (id != command.Id)
{
return ApiResponse<TodoItem>.Fail("Query id not match witch body");
}
return ApiResponse<TodoItem>.Success(await _mediator.Send(command));
}
領域事件的發布和響應
首先需要在Application/Common/Models
定義一個泛型類,實現INotification
介面,用於發布領域事件:
DomainEventNotification.cs
using MediatR;
using TodoList.Domain.Base;
namespace TodoList.Application.Common.Models;
public class DomainEventNotification<TDomainEvent> : INotification where TDomainEvent : DomainEvent
{
public DomainEventNotification(TDomainEvent domainEvent)
{
DomainEvent = domainEvent;
}
public TDomainEvent DomainEvent { get; }
}
接下來在Application/TodoItems/EventHandlers
中創建對應的Handler
:
TodoItemCompletedEventHandler.cs
using MediatR;
using Microsoft.Extensions.Logging;
using TodoList.Application.Common.Models;
using TodoList.Domain.Events;
namespace TodoList.Application.TodoItems.EventHandlers;
public class TodoItemCompletedEventHandler : INotificationHandler<DomainEventNotification<TodoItemCompletedEvent>>
{
private readonly ILogger<TodoItemCompletedEventHandler> _logger;
public TodoItemCompletedEventHandler(ILogger<TodoItemCompletedEventHandler> logger)
{
_logger = logger;
}
public Task Handle(DomainEventNotification<TodoItemCompletedEvent> notification, CancellationToken cancellationToken)
{
var domainEvent = notification.DomainEvent;
// 這裡我們還是只做日誌輸出,實際使用中根據需要進行業務邏輯處理,但是在Handler中不建議繼續Send其他Command或Notification
_logger.LogInformation("TodoList Domain Event: {DomainEvent}", domainEvent.GetType().Name);
return Task.CompletedTask;
}
}
最後去修改我們之前創建的DomainEventService
,注入IMediator
並發布領域事件,這樣就可以在Handler
中進行響應了。
DomainEventService.cs
using MediatR;
using Microsoft.Extensions.Logging;
using TodoList.Application.Common.Interfaces;
using TodoList.Application.Common.Models;
using TodoList.Domain.Base;
namespace TodoList.Infrastructure.Services;
public class DomainEventService : IDomainEventService
{
private readonly IMediator _mediator;
private readonly ILogger<DomainEventService> _logger;
public DomainEventService(IMediator mediator, ILogger<DomainEventService> logger)
{
_mediator = mediator;
_logger = logger;
}
public async Task Publish(DomainEvent domainEvent)
{
_logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name);
await _mediator.Publish(GetNotificationCorrespondingToDomainEvent(domainEvent));
}
private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent)
{
return (INotification)Activator.CreateInstance(typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!;
}
}
驗證
啟動Api
項目,更新TodoItem
的完成狀態。
-
請求
-
響應
-
領域事件發布
總結
這篇文章主要在實現PUT
請求的過程中介紹了如何通過MediatR
去響應領域事件,我們用的示例程式碼中類似「創建TodoList」,包括後面會講到的「刪除TodoItem」之類的領域事件,都是相同的處理方式,我就不一一演示了。
可以看出來,在我們這個示例應用程式的框架基本搭建完畢以後,進行領域業務的開發的思路是比較清晰的,模組之間的耦合也處在一個理想的情況。
在我們來完成CRUD
的最後一個請求之前,下一篇會簡單地介紹一下PATCH
請求的相關內容,這個請求實際應用比較少,但是為了保持知識樹的完整性,還是會過一下。