Created
October 11, 2022 02:28
-
-
Save asimmon/612b2d54f1a0d2b4e1115590d456e0be to your computer and use it in GitHub Desktop.
Efficiently reuse IMongoRunner from EphemeralMongo
This file contains hidden or 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
using EphemeralMongo; | |
public static class MongoRunnerProvider | |
{ | |
private static readonly object _lockObj = new object(); | |
private static IMongoRunner? _runner; | |
private static int _useCounter; | |
public static IMongoRunner Get() | |
{ | |
lock (_lockObj) | |
{ | |
_runner ??= MongoRunner.Run(new MongoRunnerOptions | |
{ | |
// Set shared static options | |
}); | |
_useCounter++; | |
return new MongoRunnerWrapper(_runner); | |
} | |
} | |
private sealed class MongoRunnerWrapper : IMongoRunner | |
{ | |
private IMongoRunner? _underlyingMongoRunner; | |
public MongoRunnerWrapper(IMongoRunner underlyingMongoRunner) | |
{ | |
this._underlyingMongoRunner = underlyingMongoRunner; | |
} | |
public string ConnectionString | |
{ | |
get => this._underlyingMongoRunner?.ConnectionString ?? throw new ObjectDisposedException(nameof(IMongoRunner)); | |
} | |
public void Import(string database, string collection, string inputFilePath, string? additionalArguments = null, bool drop = false) | |
{ | |
if (this._underlyingMongoRunner == null) | |
{ | |
throw new ObjectDisposedException(nameof(IMongoRunner)); | |
} | |
this._underlyingMongoRunner.Import(database, collection, inputFilePath, additionalArguments, drop); | |
} | |
public void Export(string database, string collection, string outputFilePath, string? additionalArguments = null) | |
{ | |
if (this._underlyingMongoRunner == null) | |
{ | |
throw new ObjectDisposedException(nameof(IMongoRunner)); | |
} | |
this._underlyingMongoRunner.Export(database, collection, outputFilePath, additionalArguments); | |
} | |
public void Dispose() | |
{ | |
if (this._underlyingMongoRunner != null) | |
{ | |
this._underlyingMongoRunner = null; | |
StaticDispose(); | |
} | |
} | |
private static void StaticDispose() | |
{ | |
lock (_lockObj) | |
{ | |
if (_runner != null) | |
{ | |
_useCounter--; | |
if (_useCounter == 0) | |
{ | |
_runner.Dispose(); | |
_runner = null; | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment