using System.Data;
using Galaeth.Core.Configuration;
using Galaeth.Core.Infrastructure;
using Injectio.Attributes;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Npgsql;
namespace Galaeth.DAL.Infrastructure;
///
[RegisterScoped]
public class DbConnectionProvider : IDbConnectionProvider, IAsyncDisposable
{
private readonly IOptions _databaseConfiguration;
private readonly ILogger _logger;
private NpgsqlConnection _dbConnection;
///
/// Initializes a new instance of the class.
///
/// Instance of .
/// Instance of .
public DbConnectionProvider(
IOptions databaseConfiguration,
ILogger logger)
{
_databaseConfiguration = databaseConfiguration;
_logger = logger;
}
///
public IDbConnection OpenConnection()
{
if (_dbConnection is not null)
{
if (_dbConnection.State == ConnectionState.Closed)
{
_dbConnection.Open();
}
return _dbConnection;
}
_logger.LogDebug("Opening database connection");
_dbConnection = new NpgsqlConnection(_databaseConfiguration.Value.ConnectionString);
_dbConnection.Open();
return _dbConnection;
}
///
public async Task OpenConnectionAsync()
{
if (_dbConnection is not null)
{
if (_dbConnection.State == ConnectionState.Closed)
{
await _dbConnection.OpenAsync();
}
return _dbConnection;
}
_logger.LogDebug("Opening database connection");
_dbConnection = new NpgsqlConnection(_databaseConfiguration.Value.ConnectionString);
await _dbConnection.OpenAsync();
return _dbConnection;
}
///
public async ValueTask DisposeAsync()
{
if (_dbConnection != null)
{
await _dbConnection.DisposeAsync();
}
GC.SuppressFinalize(this);
}
///
public void Dispose()
{
if (_dbConnection is null)
{
return;
}
_logger.LogDebug("Disposing database connection");
_dbConnection.Close();
_dbConnection.Dispose();
_dbConnection = null;
GC.SuppressFinalize(this);
}
}