Last active
November 30, 2017 18:07
-
-
Save feanz/a37163928c3e09e679a5 to your computer and use it in GitHub Desktop.
MongoUnitOfWork
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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