6
votes

I use the repository pattern. My repository methods receive an optional IClientSessionHandle parameter which defaults to null. A part of each method prepares the filters/updates/etc., then a call is made. Since the session is optional, I have something like this:

if (sessionHandle != null)
    await Collection.InsertOneAsync(sessionHandle, myObject);
else
    await Collection.InsertOneAsync(myObject);

I suppose that always sending the session, null or not, wouldn't work, but I did not test it yet. Also, even if it would actually work, I would have no guarantee that this behavior wouldn't change in the future, as it's not part of the contract.

Is there a way to have a single call?

PS: The reason to have an optional IClientSessionHandle is to re-use the same repository methods, within a transaction or not.

i've had to use the same pattern as there's no other alternative than calling the appropriate overload depending on wether session is null or not. - Dĵ ΝιΓΞΗΛψΚ
JohnKnoop.MongoRepository provides an abstraction that automatically enlists with the current transaction. That means you don't have to bother with the separate calls. github.com/johnknoop/MongoRepository#transactions - John Knoop
@JohnKnoop I see your useful library automatically attaches to the current transaction. Doesn't the official MongoDb.Driver work in the same way? This article medium.com/c-sharp-progarmming/… seems to imply that it does, because it does not pass the session explicitly between starting it and commiting changes. - diegosasw
All Mongo driver methods have an overload that accepts a Session object. If you don't pass in a Session object, the operation will not be part of any transaction. I'm guessing the author of the linked article must have missed this. - John Knoop