大家好,我是Edison。
組件發佈的背景
之前工作中需要用到MongoDB的事務操作,因此參考了一些資料封裝了一個小的組件,提供基礎的CRUD Repository基類 和 UnitOfWork工作單元模式。但是,我一直都沒有把它正式發佈到Nuget倉庫中,近日抽空把發佈了,大家可以搜到它並使用了。
組件具有哪些功能
EdisonTalk.MongoProxy可以提供以下幾個重要功能:
(1)提供標準的配置項注入
比如我們在appsettings中填寫如下配置,通過提供的擴展方法可以快速註冊和MongoDB的連接客戶端。這個配置項兼顧了普通賬號用戶名 以及 SSL證書驗證模式。
"MongoDatabaseConfigs": { "Servers": "xxx01.edisontalk.net,xxx02.edisontalk.net,xxx03.edisontalk.net", "Port": 27017, "ReplicaSetName": "edt-replica", "DatabaseName": "EDT_Practices", "UserName": "xxxxxxxxxxxxx", "Password": "xxxxxxxxxxxxx", "UseTLS": true, // default: false "AllowInsecureTLS": true, // default: true "SslCertificatePath": "/etc/pki/tls/certs/EDT_CA.cer" // default: null }
(2)封裝對MongoDB的Repository訪問
針對MongoDB封裝了MongoRepositoryBase的接口和實現,針對單文檔的CRUD都無需再自己實現,只需集成基類即可實現單文檔的CRUD。
(3)封裝對MongoDB的UnitOfWork操作
針對MongoDB封裝了UnitOfWork操作,針對多文檔的事務操作,使用該模式可以方便實現。
(4)封裝對MongoDB的連接字符串構造
在日常使用中,我們會用到基於配置文件構造MongoDB連接字符串的場景。比如,在CAP項目中,如果我們用到MongoDB作爲存儲,那麼就需要提供MongoDB連接字符串,因此基於標準配置項,我們提供了一個MongoDbConnUtil類用於構造連接字符串。
下面展示了CAP集成MongoDB使用MongoDbConnUtil的GetMongoDbConnectionString方法來構造:
option.UseMongoDB(option => { option.DatabaseConnection = MongoDbConnUtil.GetMongoDbConnectionString(config); ...... });
如何使用該組件:三步上籃
預備步驟:安裝組件
PM> NuGet\Install-Package EdisonTalk.MongoProxy -Version 0.0.6
第一步:注入MongoProxy核心部分
在appsettings中配置MongoDB的連接信息:
"MongoDatabaseConfigs": { "Servers": "xxx01.edisontalk.net,xxx02.edisontalk.net,xxx03.edisontalk.net", "Port": 27017, "ReplicaSetName": "edt-replica", "DatabaseName": "EDT_Practices", "UserName": "xxxxxxxxxxxxx", "Password": "xxxxxxxxxxxxx" }
然後通過擴展方法注入MongoProxy相關部分:
builder.Services.AddMongoProxy(builder.Configuration);
第二步:添加Entity 和 Repository
示例Entity:這裏的Table標籤需要指名你的集合名字,組件會自動映射上對應集合!
[Table("Orders")] public class OrderEntity : MongoEntityBase { public string OrderNumber { get; set; } public List<TransmissionEntity> Transmissions { get; set; } }
示例Repository:
public interface ITodoItemRepository : IMongoRepositoryBase<TodoItem> { } public class TodoItemRepository : MongoRepositoryBase<TodoItem>, ITodoItemRepository { public TodoItemRepository(IMongoDbContext mongoDbContext) : base(mongoDbContext) { } } services.AddScoped<ITodoItemRepository, TodoItemRepository>();
第三步:使用Repository 和 UnitOfWork
# 非事務模式 await _taskRepository.AddManyAsync(newTasks); # 事務模式(藉助UnitOfWork工作單元) private readonly IUnitOfWork _unitOfWork; public OrderService(IUnitOfWork unitOfWork, ......) { _unitOfWork = unitOfWork; ...... } public async Task Example() { using var session = await _unitOfWork.BeginTransactionAsync()) await _taskRepository.AddManyAsync(newTasks, session); await _orderRepository.AddAsync(newOrder, session); await _unitOfWork.SaveChangesAsync(session); }
小結
歡迎大家使用這個組件,我也會持續更新和完善。
附錄
GitHub:https://github.com/Coder-EdisonZhou/EdisonTalk.MongoProxy
Nuget:https://www.nuget.org/packages/EdisonTalk.MongoProxy