96 lines
2.7 KiB
C#
96 lines
2.7 KiB
C#
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;
|
|
|
|
/// <inheritdoc cref="Galaeth.Core.Infrastructure.IDbConnectionProvider" />
|
|
[RegisterScoped]
|
|
public class DbConnectionProvider : IDbConnectionProvider, IAsyncDisposable
|
|
{
|
|
private readonly IOptions<DatabaseConfiguration> _databaseConfiguration;
|
|
private readonly ILogger<DbConnectionProvider> _logger;
|
|
private NpgsqlConnection _dbConnection;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="DbConnectionProvider"/> class.
|
|
/// </summary>
|
|
/// <param name="databaseConfiguration">Instance of <see cref="IOptions{DatabaseConfiguration}"/>.</param>
|
|
/// <param name="logger">Instance of <see cref="ILogger"/>.</param>
|
|
public DbConnectionProvider(
|
|
IOptions<DatabaseConfiguration> databaseConfiguration,
|
|
ILogger<DbConnectionProvider> logger)
|
|
{
|
|
_databaseConfiguration = databaseConfiguration;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <inheritdoc cref="Galaeth.Core.Infrastructure.IDbConnectionProvider" />
|
|
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;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IDbConnection> 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;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (_dbConnection != null)
|
|
{
|
|
await _dbConnection.DisposeAsync();
|
|
}
|
|
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public void Dispose()
|
|
{
|
|
if (_dbConnection is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_logger.LogDebug("Disposing database connection");
|
|
_dbConnection.Close();
|
|
_dbConnection.Dispose();
|
|
_dbConnection = null;
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
}
|