博主最近失業在家,找工作之余,看了一些關于洋蔥(整潔)架構的資料和項目,有感而發,自己動手寫了個洋蔥架構解決方案,起名叫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,包括分頁查詢,方便和其它實體連接后再篩選查詢字段。
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。
開發人員只需要在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 AddCategoryCommandValidator : AbstractValidator<AddCategoryCommand>
{
public AddCategoryCommandValidator()
{
RuleFor(x => x.Model.CategoryName).NotEmpty().WithMessage(p => "類別名稱不能為空.");
}
}
11.請求日志和性能日志記錄
基于MediatR 管道實現請求日志和性能日志記錄。
12. 全局異常捕獲記錄
基于MediatR 異常接口實現異常捕獲。
三、相關技術如下
* .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.