I took a look at the clientEncryption.Encrypt method source code on GitHub and found a possible way to improve the memory management in the MongoDB.Driver.Encryption.ExplicitEncryptionLibMongoCryptController class.
The EncryptField and EncryptFieldAsync methods both call UnwrapValue, which is:
private BsonValue UnwrapValue(byte[] encryptedWrappedBytes)
{
var rawDocument = new RawBsonDocument(encryptedWrappedBytes);
return rawDocument["v"];
}
As RawBsonDocument is IDisposable, it should be surrounded by a using clause:
private BsonValue UnwrapValue(byte[] encryptedWrappedBytes)
{
using var rawDocument = new RawBsonDocument(encryptedWrappedBytes);
return rawDocument["v"];
}
Not sure whether it could solve the issue, or not, but there may be something to explore further?