refactor: implement IDisposable interface in NoSqlDbContext for proper resource management

This commit is contained in:
Jean Gatto
2025-02-08 09:48:54 -03:00
parent 595ace1310
commit dfec184cb2
3 changed files with 41 additions and 8 deletions
@@ -1,3 +1,4 @@
using System;
using System.Threading.Tasks;
using MongoDB.Driver;
@@ -6,7 +7,7 @@ namespace Shop.Query.Abstractions;
/// <summary>
/// Represents the read-only database context for querying data.
/// </summary>
public interface IReadDbContext
public interface IReadDbContext : IDisposable
{
/// <summary>
/// Gets the connection string for the database.
@@ -7,7 +7,7 @@ namespace Shop.Query.Abstractions;
/// <summary>
/// Represents a contract for synchronizing query models with the database.
/// </summary>
public interface ISynchronizeDb
public interface ISynchronizeDb : IDisposable
{
/// <summary>
/// Upserts a query model into the database.
+38 -6
View File
@@ -34,7 +34,8 @@ public sealed class NoSqlDbContext : IReadDbContext, ISynchronizeDb
Sparse = true
};
private readonly IMongoDatabase _database;
private readonly MongoClient _mongoClient;
private readonly IMongoDatabase _mongoDatabase;
private readonly ILogger<NoSqlDbContext> _logger;
private readonly AsyncRetryPolicy _mongoRetryPolicy;
@@ -42,8 +43,8 @@ public sealed class NoSqlDbContext : IReadDbContext, ISynchronizeDb
{
ConnectionString = options.Value.NoSqlConnection;
var mongoClient = new MongoClient(options.Value.NoSqlConnection);
_database = mongoClient.GetDatabase(DatabaseName);
_mongoClient = new MongoClient(options.Value.NoSqlConnection);
_mongoDatabase = _mongoClient.GetDatabase(DatabaseName);
_logger = logger;
_mongoRetryPolicy = CreateRetryPolicy(logger);
}
@@ -55,11 +56,11 @@ public sealed class NoSqlDbContext : IReadDbContext, ISynchronizeDb
public string ConnectionString { get; }
public IMongoCollection<TQueryModel> GetCollection<TQueryModel>() where TQueryModel : IQueryModel =>
_database.GetCollection<TQueryModel>(typeof(TQueryModel).Name);
_mongoDatabase.GetCollection<TQueryModel>(typeof(TQueryModel).Name);
public async Task CreateCollectionsAsync()
{
using var asyncCursor = await _database.ListCollectionNamesAsync();
using var asyncCursor = await _mongoDatabase.ListCollectionNamesAsync();
var collections = await asyncCursor.ToListAsync();
foreach (var collectionName in GetCollectionNamesFromAssembly())
@@ -69,7 +70,7 @@ public sealed class NoSqlDbContext : IReadDbContext, ISynchronizeDb
{
_logger.LogInformation("----- MongoDB: creating the Collection {Name}", collectionName);
await _database.CreateCollectionAsync(collectionName, new CreateCollectionOptions
await _mongoDatabase.CreateCollectionAsync(collectionName, new CreateCollectionOptions
{
ValidationLevel = DocumentValidationLevel.Strict
});
@@ -154,4 +155,35 @@ public sealed class NoSqlDbContext : IReadDbContext, ISynchronizeDb
logger.LogError(ex, "An unexpected exception occurred while saving to MongoDB: {Message}", ex.Message);
#endregion
#region IDisposable
// To detect redundant calls.
private bool _disposed;
// Public implementation of Dispose pattern callable by consumers.
~NoSqlDbContext() => Dispose(false);
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
private void Dispose(bool disposing)
{
if (_disposed)
return;
// Dispose managed state (managed objects).
if (disposing)
_mongoClient.Dispose();
_disposed = true;
}
#endregion
}