Skip to content

Instantly share code, notes, and snippets.

@feanz
Last active November 30, 2017 18:07
Show Gist options
  • Save feanz/a37163928c3e09e679a5 to your computer and use it in GitHub Desktop.
Save feanz/a37163928c3e09e679a5 to your computer and use it in GitHub Desktop.
MongoUnitOfWork
public static class MongoUnitOfWork
{
public static async Task Transaction(this IMongoDatabase database, Func<Task> commands)
{
if (database == null) throw new ArgumentNullException("database");
var commited = false;
var beginTransaction = new BsonDocument("beginTransaction", "true");
await database.RunCommandAsync<BsonDocument>(beginTransaction);
while (!commited)
{
try
{
commands();
commited = true;
var commitTransaction = new BsonDocument("commitTransaction", "true");
await database.RunCommandAsync<BsonDocument>(commitTransaction);
}
catch (Exception)
{
var retryTransaction = new BsonDocument(new[] {
new BsonElement("beginTransaction", "true"),
new BsonElement("retry","true")
});
database.RunCommandAsync<BsonDocument>(retryTransaction).Wait();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment