OnionArch - 採用DDD+CQRS+.Net 7.0實現的洋蔥架構

博主最近失業在家,找工作之餘,看了一些關於洋蔥(整潔)架構的資料和項目,有感而發,自己動手寫了個洋蔥架構解決方案,起名叫OnionArch。基於最新的.Net 7.0 RC1, 數據庫採用PostgreSQL, 目前實現了包括多租戶在內的12個特性。

該架構解決方案主要參考了NorthwindTraders sample-dotnet-core-cqrs-api 項目, B站上楊中科的課程代碼以及博主的一些項目經驗。

洋蔥架構的示意圖如下:

 

一、OnionArch 解決方案說明

解決方案截圖如下:

 

可以看到,該解決方案輕量化實現了洋蔥架構,每個層都只用一個項目表示。建議將該解決方案作爲單個微服務使用,不建議在領域層包含太多的領域根。

源代碼分爲四個項目:

1. OnionArch.Domain

- 核心領域層,類庫項目,其主要職責實現每個領域內的業務邏輯。設計每個領域的實體(Entity),值對象、領域事件和領域服務,在領域服務中封裝業務邏輯,爲應用層服務。
- 領域層也包含數據庫倉儲接口,緩存接口、工作單元接口、基礎實體、基礎領域跟實體、數據分頁實體的定義,以及自定義異常等。

2. OnionArch.Infrastructure

- 基礎架構層,類庫項目,其主要職責是實現領域層定義的各種接口適配器(Adapter)。例如數據庫倉儲接口、工作單元接口和緩存接口,以及領域層需要的其它系統集成接口。
- 基礎架構層也包含Entity Framework基礎DbConext、ORM配置的定義和數據遷移記錄。

3. OnionArch.Application

- 應用(業務用例)層,類庫項目,其主要職責是通過調用領域層服務實現業務用例。一個業務用例通過調用一個或多個領域層服務實現。不建議在本層實現業務邏輯。
- 應用(業務用例)層也包含業務用例實體(Model)、Model和Entity的映射關係定義,業務實基礎命令接口和查詢接口的定義(CQRS),包含公共MediatR管道(AOP)處理和公共Handler的處理邏輯。

4. OnionArch.GrpcService

- 界面(API)層,GRPC接口項目,用於實現GRPC接口。通過MediatR特定業務用例實體(Model)消息來調用應用層的業務用例。
- 界面(API)層也包含對領域層接口的實現,例如通過HttpContext獲取當前租戶和賬號登錄信息。

二、OnionArch已實現特性說明

1.支持多租戶(通過租戶字段)

基於Entity Framework實體過濾器和實現對租戶數據的查詢過濾

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//加載配置
modelBuilder.ApplyConfigurationsFromAssembly(typeof(TDbContext).Assembly);

//爲每個繼承BaseEntity實體增加租戶過濾器
// Set BaseEntity rules to all loaded entity types
foreach (var entityType in GetBaseEntityTypes(modelBuilder))
{
var method = SetGlobalQueryMethod.MakeGenericMethod(entityType);
method.Invoke(this, new object[] { modelBuilder, entityType });
}
}

在BaseDbContext文件的SaveChanges之前對實體租戶字段賦值

//爲每個繼承BaseEntity的實體的Id主鍵和TenantId賦值
var baseEntities = ChangeTracker.Entries<BaseEntity>();
foreach (var entry in baseEntities)
{
switch (entry.State)
{
case EntityState.Added:
if (entry.Entity.Id == Guid.Empty)
entry.Entity.Id = Guid.NewGuid();
if (entry.Entity.TenantId == Guid.Empty)
entry.Entity.TenantId = _currentTenantService.TenantId;
break;
}
}

多租戶支持全部在底層實現,包括租戶字段的索引配置等。開發人員不用關心多租戶部分的處理邏輯,只關注業務領域邏輯也業務用例邏輯即可。

2.通用倉儲和緩存接口

實現了泛型通用倉儲接口,批量更新和刪除方法基於最新的Entity Framework 7.0 RC1,爲提高查詢效率,查詢方法全部返回IQueryable,包括分頁查詢,方便和其它實體連接後再篩選查詢字段。

public interface IBaseRepository<TEntity> where TEntity : BaseEntity
{
Task<TEntity> Add(TEntity entity);
Task AddRange(params TEntity[] entities);

Task<TEntity> Update(TEntity entity);
Task<int> UpdateRange(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<SetPropertyCalls<TEntity>, SetPropertyCalls<TEntity>>> setPropertyCalls);
Task<int> UpdateByPK(Guid Id, Expression<Func<SetPropertyCalls<TEntity>, SetPropertyCalls<TEntity>>> setPropertyCalls);


Task<TEntity> Delete(TEntity entity);
Task<int> DeleteRange(Expression<Func<TEntity, bool>> whereLambda);
Task<int> DeleteByPK(Guid Id);
Task<TEntity> DeleteByPK2(Guid Id);


Task<TEntity> SelectByPK(Guid Id);
IQueryable<TEntity> SelectRange<TOrder>(Expression<Func<TEntity, bool>> whereLambda, Expression<Func<TEntity, TOrder>> orderbyLambda, bool isAsc = true);
Task<PagedResult<TEntity>> SelectPaged<TOrder>(Expression<Func<TEntity, bool>> whereLambda, PagedOption pageOption, Expression<Func<TEntity, TOrder>> orderbyLambda, bool isAsc = true);

Task<bool> IsExist(Expression<Func<TEntity, bool>> whereLambda);
}
View Code

3.領域事件自動發佈和保存

在BaseDbContext文件的SaveChanges之前從實體中獲取領域事件併發布領域事件和保存領域事件通知,以備後查。

//所有包含領域事件的領域跟實體
var haveEventEntities = domainRootEntities.Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any()).ToList();
//所有的領域事件
var domainEvents = haveEventEntities
.SelectMany(x => x.Entity.DomainEvents)
.ToList();
//根據領域事件生成領域事件通知
var domainEventNotifications = new List<DomainEventNotification>();
foreach (var domainEvent in domainEvents)
{
domainEventNotifications.Add(new DomainEventNotification(nowTime, _currentUserService.UserId, domainEvent.EventType, JsonConvert.SerializeObject(domainEvent)));
}
//清除所有領域根實體的領域事件
haveEventEntities
.ForEach(entity => entity.Entity.ClearDomainEvents());
//生成領域事件任務並執行
var tasks = domainEvents
.Select(async (domainEvent) =>
{
await _mediator.Publish(domainEvent);
});
await Task.WhenAll(tasks);
//保存領域事件通知到數據表中
DomainEventNotifications.AddRange(domainEventNotifications);

領域事件發佈和通知保存在底層實現。開發人員不用關心領域事件發佈和保存邏輯,只關注於領域事件的定義和處理即可。

4.領域根實體審計信息自動記錄

在BaseDbContext文件的Savechanges之前對記錄領域根實體的審計信息。

//爲每個繼承AggregateRootEntity領域跟的實體的AddedBy,Added,LastModifiedBy,LastModified賦值
//爲刪除的實體生成實體刪除領域事件

DateTime nowTime = DateTime.UtcNow;
var domainRootEntities = ChangeTracker.Entries<AggregateRootEntity>();
foreach (var entry in domainRootEntities)
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.AddedBy = _currentUserService.UserId;
entry.Entity.Added = nowTime;
break;
case EntityState.Modified:
entry.Entity.LastModifiedBy = _currentUserService.UserId;
entry.Entity.LastModified = nowTime;
break;
case EntityState.Deleted:
EntityDeletedDomainEvent entityDeletedDomainEvent = new EntityDeletedDomainEvent(
_currentUserService.UserId,
entry.Entity.GetType().Name,
entry.Entity.Id,
JsonConvert.SerializeObject(entry.Entity)
);
entry.Entity.AddDomainEvent(entityDeletedDomainEvent);
break;
}
}

領域根實體審計信息記錄在底層實現。開發人員不用關心審計字段的處理邏輯。

5. 回收站式軟刪除

採用回收站式軟刪除而不採用刪除字段的軟刪除方式,是爲了避免垃圾數據和多次刪除造成的唯一索引問題。
自動生成和發佈實體刪除的領域事件,代碼如上。
通過MediatR Handler,接收實體刪除領域事件,將已刪除的實體保存到回收站中。

public class EntityDeletedDomainEventHandler : INotificationHandler<EntityDeletedDomainEvent>
{
private readonly RecycleDomainService _domainEventService;

public EntityDeletedDomainEventHandler(RecycleDomainService domainEventService)
{
_domainEventService = domainEventService;
}


public async Task Handle(EntityDeletedDomainEvent notification, CancellationToken cancellationToken)
{
var eventData = JsonSerializer.Serialize(notification);
RecycledEntity entity = new RecycledEntity(notification.OccurredOn, notification.OccurredBy, notification.EntityType, notification.EntityId, notification.EntityData);
await _domainEventService.AddRecycledEntity(entity);
}
}

6.CQRS(命令查詢分離)

通過MediatR IRequest 實現了ICommand接口和Iquery接口,業務用例請求命令或者查詢繼承該接口即可。

public interface ICommand : IRequest
{
}

public interface ICommand<out TResult> : IRequest<TResult>
{
}
public interface IQuery<out TResult> : IRequest<TResult>
{

}
public class AddCategoryCommand : ICommand
{
public AddCategoryRequest Model { get; set; }
}

代碼中的AddCategoryCommand 增加類別命令繼承ICommand。

7.自動工作單元Commit

通過MediatR 管道實現了業務Command用例完成後自動Commit,開發人員不需要手動提交。

public class UnitOfWorkProcessor<TRequest, TResponse> : IRequestPostProcessor<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
private readonly IUnitOfWork _unitOfWork;

public UnitOfWorkProcessor(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public async Task Process(TRequest request, TResponse response, CancellationToken cancellationToken)
{
if (request is ICommand || request is ICommand<TResponse>)
{
await _unitOfWork.CommitAsync();
}
}
}

8.GRPC Message做爲業務用例實體

通過將GRPC proto文件放入Application項目,重用其生成的message作爲業務用例實體(Model)。

public class AddCategoryCommand : ICommand
{
public AddCategoryRequest Model { get; set; }
}

其中AddCategoryRequest 爲proto生成的message。

9.通用CURD業務用例

在應用層分別實現了CURD的Command(增改刪)和Query(查詢) Handler。

public class CUDCommandHandler<TModel, TEntity> : IRequestHandler<CUDCommand<TModel>> where TEntity : BaseEntity
{
private readonly CURDDomainService<TEntity> _curdDomainService;

public CUDCommandHandler(CURDDomainService<TEntity> curdDomainService)
{
_curdDomainService = curdDomainService;
}

public async Task<Unit> Handle(CUDCommand<TModel> request, CancellationToken cancellationToken)
{
TEntity entity = null;
if (request.Operation == "C" || request.Operation == "U")
{
if (request.Model == null)
{
throw new BadRequestException($"the model of this request is null");
}
entity = request.Model.Adapt<TEntity>();
if (entity == null)
{
throw new ArgumentNullException($"the entity of {nameof(TEntity)} is null");
}
}
if (request.Operation == "U" || request.Operation == "D")
{
if (request.Id == Guid.Empty)
{
throw new BadRequestException($"the Id of this request is null");
}
}

switch (request.Operation)
{
case "C":
await _curdDomainService.Create(entity);
break;
case "U":
await _curdDomainService.Update(entity);
break;
case "D":
await _curdDomainService.Delete(request.Id);
break;
}

return Unit.Value;
}
}
View Code

開發人員只需要在GRPC層簡單調用即可實現CURD業務。

public async override Task<AddProductReply> AddProduct(AddProductRequest request, ServerCallContext context)
{
CUDCommand<AddProductRequest> addProductCommand = new CUDCommand<AddProductRequest>();
addProductCommand.Id = Guid.NewGuid();
addProductCommand.Model = request;
addProductCommand.Operation = "C";
await _mediator.Send(addProductCommand);
return new AddProductReply()
{
Message = "Add Product sucess"
};
}

10. 業務實體驗證

通過FluentValidation和MediatR 管道實現業務實體自動驗證,並自動拋出自定義異常。

public class RequestValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;

public RequestValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}

public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var errors = _validators
.Select(v => v.Validate(request))
.SelectMany(result => result.Errors)
.Where(error => error != null)
.ToList();

if (errors.Any())
{
var errorBuilder = new StringBuilder();

errorBuilder.AppendLine("Invalid Request, reason: ");

foreach (var error in errors)
{
errorBuilder.AppendLine(error.ErrorMessage);
}

throw new InvalidRequestException(errorBuilder.ToString(), null);
}
return await next();
}
}
View Code

開發人員只需要定義驗證規則即可

public class AddCategoryCommandValidator : AbstractValidator<AddCategoryCommand>
{
public AddCategoryCommandValidator()
{
RuleFor(x => x.Model.CategoryName).NotEmpty().WithMessage(p => "類別名稱不能爲空.");
}
}

11.請求日誌和性能日誌記錄

基於MediatR 管道實現請求日誌和性能日誌記錄。

public class RequestPerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
private readonly Stopwatch _timer;
private readonly ILogger<TRequest> _logger;
private readonly ICurrentUserService _currentUserService;
private readonly ICurrentTenantService _currentTenantService;

public RequestPerformanceBehaviour(ILogger<TRequest> logger, ICurrentUserService currentUserService, ICurrentTenantService currentTenantService)
{
_timer = new Stopwatch();

_logger = logger;
_currentUserService = currentUserService;
_currentTenantService = currentTenantService;
}

public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
_timer.Start();

var response = await next();

_timer.Stop();

if (_timer.ElapsedMilliseconds > 500)
{
var name = typeof(TRequest).Name;

_logger.LogWarning("Request End: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}",
name, _timer.ElapsedMilliseconds, _currentUserService.UserId, request);
}

return response;
}
}
View Code

12. 全局異常捕獲記錄

基於MediatR 異常接口實現異常捕獲。

public class CommonExceptionHandler<TRequest, TResponse, TException> : IRequestExceptionHandler<TRequest, TResponse, TException>
where TException : Exception where TRequest: IRequest<TResponse>
{
private readonly ILogger<CommonExceptionHandler<TRequest, TResponse,TException>> _logger;
private readonly ICurrentUserService _currentUserService;
private readonly ICurrentTenantService _currentTenantService;

public CommonExceptionHandler(ILogger<CommonExceptionHandler<TRequest, TResponse, TException>> logger, ICurrentUserService currentUserService, ICurrentTenantService currentTenantService)
{
this._logger = logger;
_currentUserService = currentUserService;
_currentTenantService = currentTenantService;
}

public Task Handle(TRequest request, TException exception, RequestExceptionHandlerState<TResponse> state, CancellationToken cancellationToken)
{
var name = typeof(TRequest).Name;

_logger.LogError(exception, $"Request Error: {name} {state} Tenant:{_currentTenantService.TenantId} User:{_currentUserService.UserId}", request);

//state.SetHandled();
return Task.CompletedTask;
}

}
View Code

三、相關技術如下

* .NET Core 7.0 RC1

* ASP.NET Core 7.0 RC1

* Entity Framework Core 7.0 RC1

* MediatR 10.0.1

* Npgsql.EntityFrameworkCore.PostgreSQL 7.0.0-rc.1

* Newtonsoft.Json 13.0.1

* Mapster 7.4.0-pre03

* FluentValidation.AspNetCore 11.2.2

* GRPC.Core 2.46.5

四、 找工作

博主有10年以上的軟件技術實施經驗(Tech Leader),專注於軟件架構設計、軟件開發和構建,專注於微服務和雲原生(K8s)架構, .Net Core\Java開發和Devops。

博主有10年以上的軟件交付管理經驗(Project Manager,Product Ower),專注于敏捷(Scrum)項目管理、軟件產品業務分析和原型設計。

博主能熟練配置和使用 Microsoft Azure 和Microsoft 365 雲平臺,獲得相關微軟認證和證書。

我家在廣州,也可以去深圳工作。做架構和項目管理都可以,希望能從事穩定行業的業務數字化轉型。有工作機會推薦的朋友可以加我微信 15920128707,微信名字叫Jerry.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章