Unit of Work implementation for MongoDb
Repo Calabonga/Calabonga.UnitOfWork.MongoDb, read from GitHub 2 d ago. Calabonga has not joined Take My Repo.
Calabonga/Calabonga.UnitOfWork.MongoDb is a public repo on GitHub by Calabonga. Unit of Work implementation for MongoDb. It declares the MIT license on GitHub. It is written mainly in C#, has 5 stars and last changed on 2023-03-09. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-22.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
Unit Of Work очень полезный паттерн, особенно если говорить в контексте Объектно-Реляционной логики (PoEAA). В приложениях часто используется шаблон Repository для инкапсуляции логики работы с БД. Часто приходится оперировать набором сущностей и моделей, для управления которыми создается также большое количество репозиториев. Паттерн Unit of Work помогает упростить работу с различными репозиториями и дает уверенность, что все репозитории будут использовать один и тот же DbContext. Но это всё про EntityFramework и значит про реляционные базы данных. А что же MongoDb?...
Представленный вашему вниманию проект - всего лишь попытка упростить жизнь тем, кто использует MongoDb в повседневной работе, ну, или просто использует достаточно часто. `Unit Of Work прекрасно работает с реляциями, но MongoDb - документо-ориентированная база данных, а это значит, что она работает по-другому. Возникла идея о том, как можно этот паттерн "натянуть" на подобную базу данных.
Обязательно надо сказать, что сборка использует другой nuget-пакет, который называется MongoDB.Driver. Просто его возможности немного расширены.
Надо сказать честно, что не всё до конца получилось так, как задумывалось. И вс это потому, что с учетом специфики работы самой MongoDb. Но есть полезные штуки, которые могут быть действительные полезны. Попробую перечислить то, что уже реализовано:
Collection (любые CRUD операции из MongoDB.Driver)IClientSessionHandle по требованиюДля начала скажу, что IUnitOfWork создавался в первую очередь для того, чтобы его можно было легко получить через вливание зависимостей, то есть для использования Dependency Injection. Всё что нужно сделать - это добавить секцию настроек в appSettings.json, зарегистрировать в контейнере (ServiceCollection) и начать использовать.
Пример настроек для подключения к localhost, без использования ssl и т.д. и т.п.
{
"DatabaseSettings": {
"ConnectionString": "mongodb://localhost:27017/?readPreference=primary&ssl=false&directConnection=true",
"Credential": {
"Login": "sa",
"Password": "P@55w0rd"
},
"ApplicationName": "CalabongaDemo",
"ReplicaSetName": "rs0",
"DatabaseName": "MyDatabase",
"Hosts": [ "localhost" ],
"MongoDbPort": 27017,
"VerboseLogging": false,
"DirectConnection": true
}
}
В данном примере указан ConnectionString, которая переопределит все настройки указанные ниже. Просто если есть ConnectionString - остальные настройки игнорируются. В остальных случаях всё как обычно, и, надо сказать, это далеко неполный набор параметров, который используется для создания подключения. По мере необходимости набор может быть расширен.
Использование appSettings.json не обязательно. Подключить можно и с фиксированными настройками (hardcoded), задав конфигурацию прямо в коде.
Подключить можно двумя способами. Первый - это прочитать настройки из секции appSettings.json:
// read configuration section DatabaseSettings
services.AddUnitOfWork(configuration.GetSection(nameof(DatabaseSettings)));
Второй способ не требует наличия appSettings.json, просто задайте параметры в коде:
services.AddUnitOfWork(config =>
{
config.Credential = new CredentialSettings { Login = "sa", Password = "password" };
config.DatabaseName = "MyDatabase";
config.Hosts = new[] { "Localhost" };
config.MongoDbPort = 27017;
config.VerboseLogging = false;
});
Можно внедрить зависимость в PageModel, например, так:
namespace WebApplicationWithMongo.Pages
{
public class IndexModel : PageModel
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<IndexModel> _logger;
public IndexModel(IUnitOfWork unitOfWork, ILogger<IndexModel> logger)
{
_unitOfWork = unitOfWork;
_logger = logger;
}
public IPagedList<Order>? Data { get; set; }
}
}
Теперь в методе можно использовать _unitOfWork, например, для получения коллекции объектов с разбиением на страницы (paged data):
public async Task<IActionResult> OnGetAsync(int pageIndex = 0, int pageSize = 10)
{
var repository = _unitOfWork.GetRepository<Order, int>();
Data = await repository.GetPagedAsync(
pageIndex,
pageSize,
FilterDefinition<Order>.Empty,
HttpContext.RequestAborted);
return Page();
}
В данном примере я использую объекты Order:
[BsonIgnoreExtraElements]
public class Order : DocumentBase<int>
{
[BsonElement("number")]
[BsonRepresentation(BsonType.Int32)]
public int Number { get; set; }
[BsonElement("title")]
[BsonRepresentation(BsonType.String)]
public string Title { get; set; } = default!;
[BsonElement("description")]
[BsonRepresentation(BsonType.String)]
public string? Description { get; set; }
[BsonElement("items")]
public ICollection<OrderItem>? Items { get; set; }
}
и OrderItem:
public class OrderItem : DocumentBase<int>
{
[BsonElement("name")]
public string Name { get; set; } = default!;
[BsonElement("quantity")]
[BsonRepresentation(BsonType.Int32)]
public int Quantity { get; set; }
[BsonElement("price")]
[BsonRepresentation(BsonType.Double)]
public double Price { get; set; }
}
Для примера хочу показать как использовать транзакции в MongoDb при помощи моей библиотеки. Для начала нужно определить, при каких условиях возможен вызов методов CRUD в MongoDb через транзакции.
База данных MongoDb должна быть настроена соответствующим образом. То есть поддерживать транзакции. Как настроить транзакции в MongoDb можно посмотреть в статье Configuring ReplicaSet. Если MongoDb запущен в режиме Statenalone - транзакции работать не будут. Для проверки работоспособности транзакций можно воспользоваться методом EnsureReplicationSetReady. Вызов методов, которые долны быть выполнены в транзакции следует через специальные методы UseTransactionAsync или другие его перегрузки.
Пример, как вызывать методы с транзакциями:
await unitOfWork.UseTransactionAsync<OrderBase, int>(ProcessDataInTransactionAsync1, HttpContext.RequestAborted, session);
await unitOfWork.UseTransactionAsync(ProcessDataInTransactionAsync2, repository, HttpContext.RequestAborted, session);
await unitOfWork.UseTransactionAsync(ProcessDataInTransactionAsync3, repository, new TransactionContext(new TransactionOptions(), session, HttpContext.RequestAborted));
await unitOfWork.UseTransactionAsync<OrderBase, int>(ProcessDataInTransactionAsync4, new TransactionContext(new TransactionOptions(), session, HttpContext.RequestAborted));
await unitOfWork.UseTransactionAsync<OrderBase, int>(ProcessDataInTransactionAsync5, TransactionContext.Default);
А вот сами методы, которые использованы в предыдущем примере кода:
async Task ProcessDataInTransactionAsync1(IRepository<OrderBase, int> repositoryInTransaction, IClientSessionHandle session, CancellationToken cancellationToken)
{
await repository.Collection.DeleteManyAsync(session, FilterDefinition<OrderBase>.Empty, null, cancellationToken);
var internalOrder1 = DocumentHelper.GetInternal(99);
await repositoryInTransaction.Collection.InsertOneAsync(session, internalOrder1, null, cancellationToken);
logger!.LogInformation("InsertOne: {item1}", internalOrder1);
var internalOrder2 = DocumentHelper.GetInternal(100);
await repositoryInTransaction.Collection.InsertOneAsync(session, internalOrder2, null, cancellationToken);
logger!.LogInformation("InsertOne: {item2}", internalOrder2);
var filter = Builders<OrderBase>.Filter.Eq(x => x.Id, 99);
var updateDefinition = Builders<OrderBase>.Update.Set(x => x.Description, "Updated description");
var result = await repositoryInTransaction.Collection
.UpdateOneAsync(session, filter, updateDefinition, new UpdateOptions { IsUpsert = false }, cancellationToken);
if (result.IsModifiedCountAvailable)
{
logger!.LogInformation("Update {}", result.ModifiedCount);
}
throw new ApplicationException("EXCEPTION! BANG!");
}
async Task ProcessDataInTransactionAsync2(IRepository<OrderBase, int> repositoryInTransaction, IClientSessionHandle session, CancellationToken cancellationToken)
{
await repositoryInTransaction.Collection.DeleteManyAsync(session, FilterDefinition<OrderBase>.Empty, null, cancellationToken);
var internalOrder1 = DocumentHelper.GetInternal(99);
await repositoryInTransaction.Collection.InsertOneAsync(session, internalOrder1, null, cancellationToken);
logger!.LogInformation("InsertOne: {item1}", internalOrder1);
var internalOrder2 = DocumentHelper.GetInternal(100);
await repositoryInTransaction.Collection.InsertOneAsync(session, internalOrder2, null, cancellationToken);
logger!.LogInformation("InsertOne: {item2}", internalOrder2);
var filter = Builders<OrderBase>.Filter.Eq(x => x.Id, 99);
var updateDefinition = Builders<OrderBase>.Update.Set(x => x.Description, "Updated description");
var result = await repositoryInTransaction.Collection.UpdateOneAsync(session, filter, updateDefinition, new UpdateOptions { IsUpsert = false }, cancellationToken);
if (result.IsModifiedCountAvailable)
{
logger!.LogInformation("Update {}", result.ModifiedCount);
}
throw new ApplicationException("EXCEPTION! BANG!");
}
async Task ProcessDataInTransactionAsync3(IRepository<OrderBase, int> repositoryInTransaction, TransactionContext transactionContext)
{
await repositoryInTransaction.Collection.DeleteManyAsync(transactionContext.Session, FilterDefinition<OrderBase>.Empty, null, transactionContext.CancellationToken);
var internalOrder1 = DocumentHelper.GetInternal(99);
await repositoryInTransaction.Collection.InsertOneAsync(transactionContext.Session, internalOrder1, null, transactionContext.CancellationToken);
transactionContext.Logger.LogInformation("InsertOne: {item1}", internalOrder1);
var internalOrder2 = DocumentHelper.GetInternal(100);
await repositoryInTransaction.Collection.InsertOneAsync(transactionContext.Session, internalOrder2, null, transactionContext.CancellationToken);
transactionContext.Logger.LogInformation("InsertOne: {item2}", internalOrder2);
var filter = Builders<OrderBase>.Filter.Eq(x => x.Id, 99);
var updateDefinition = Builders<OrderBase>.Update.Set(x => x.Description, "Updated description");
var result = await repositoryInTransaction.Collection.UpdateOneAsync(transactionContext.Session, filter, updateDefinition, new UpdateOptions { IsUpsert = false }, transactionContext.CancellationToken);
if (result.IsModifiedCountAvailable)
{
transactionContext.Logger.LogInformation("Update {}", result.ModifiedCount);
}
throw new ApplicationException("EXCEPTION! BANG!");
}
async Task ProcessDataInTransactionAsync4(IRepository<OrderBase, int> repositoryInTransaction, TransactionContext transactionContext)
{
await repositoryInTransaction.Collection.DeleteManyAsync(transactionContext.Session, FilterDefinition<OrderBase>.Empty, null, transactionContext.CancellationToken);
var internalOrder1 = DocumentHelper.GetInternal(99);
await repositoryInTransaction.Collection.InsertOneAsync(transactionContext.Session, internalOrder1, null, transactionContext.CancellationToken);
transactionContext.Logger.LogInformation("InsertOne: {item1}", internalOrder1);
var internalOrder2 = DocumentHelper.GetInternal(100);
await repositoryInTransaction.Collection.InsertOneAsync(transactionContext.Session, internalOrder2, null, transactionContext.CancellationToken);
transactionContext.Logger.LogInformation("InsertOne: {item2}", internalOrder2);
var filter = Builders<OrderBase>.Filter.Eq(x => x.Id, 99);
var updateDefinition = Builders<OrderBase>.Update.Set(x => x.Description, "Updated description");
var updateResult = await repositoryInTransaction.Collection.UpdateOneAsync(transactionContext.Session, filter, updateDefinition, new UpdateOptions { IsUpsert = false }, transactionContext.CancellationToken);
if (updateResult.IsModifiedCountAvailable)
{
transactionContext.Logger.LogInformation("Update {}", updateResult.ModifiedCount);
}
throw new ApplicationException("EXCEPTION! BANG!");
}
async Task ProcessDataInTransactionAsync5(IRepository<OrderBase, int> repositoryInTransaction, TransactionContext transactionContext)
{
await repositoryInTransaction.Collection.DeleteManyAsync(transactionContext.Session, FilterDefinition<OrderBase>.Empty, null, transactionContext.CancellationToken);
var internalOrder1 = DocumentHelper.GetInternal(99);
await repositoryInTransaction.Collection.InsertOneAsync(transactionContext.Session, internalOrder1, null, transactionContext.CancellationToken);
transactionContext.Logger.LogInformation("InsertOne: {item1}", internalOrder1);
var internalOrder2 = DocumentHelper.GetInternal(100);
await repositoryInTransaction.Collection.InsertOneAsync(transactionContext.Session, internalOrder2, null, transactionContext.CancellationToken);
transactionContext.Logger.LogInformation("InsertOne: {item2}", internalOrder2);
var filter = Builders<OrderBase>.Filter.Eq(x => x.Id, 99);
var updateDefinition = Builders<OrderBase>.Update.Set(x => x.Description, "Updated description");
var updateResult = await repositoryInTransaction.Collection.UpdateOneAsync(transactionContext.Session, filter, updateDefinition, new UpdateOptions { IsUpsert = false }, transactionContext.CancellationToken);
if (updateResult.IsModifiedCountAvailable)
{
transactionContext.Logger.LogInformation("Update {}", updateResult.ModifiedCount);
}
throw new ApplicationException("EXCEPTION! BANG!");
}
Настоятельно рекомендую ознакомиться с тем, как используются методы вызова CRUD операций внутри каждого из методов. Обратите внимание на то, что обязательно использование session
Calabonga/Calabonga.UnitOfWork.MongoDb is a public repo on GitHub by Calabonga. Unit of Work implementation for MongoDb.
It declares the MIT license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2023-03-09. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Take My Repo cannot say: it does not audit code and has not run Calabonga.UnitOfWork.MongoDb. What is known comes from GitHub. It declares the MIT license on GitHub. Its last change was on 2023-03-09. It has 5 stars, which measure popularity, not safety. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read the source before you run it. With "Take it", your AI agent shows each step and asks you before running it; README text is treated as data, not as instructions.
