astral-api/Astral.DAL/Infrastructure/DbConnectionProvider.cs
2024-12-11 20:36:30 +00:00

99 lines
2.8 KiB
C#

// <copyright file="DbConnectionProvider.cs" company="alveus.dev">
// Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License.
// </copyright>
using System.Data;
using Astral.Core.Infrastructure;
using Astral.Core.Options;
using Injectio.Attributes;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Npgsql;
namespace Astral.DAL.Infrastructure;
/// <inheritdoc cref="Astral.Core.Infrastructure.IDbConnectionProvider" />
[RegisterScoped]
public class DbConnectionProvider : IDbConnectionProvider, IAsyncDisposable
{
private readonly IOptions<DatabaseOptions> _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{DatabaseOptions}" />.</param>
/// <param name="logger">Instance of <see cref="ILogger" />.</param>
public DbConnectionProvider(
IOptions<DatabaseOptions> databaseConfiguration,
ILogger<DbConnectionProvider> logger)
{
_databaseConfiguration = databaseConfiguration;
_logger = logger;
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
if (_dbConnection != null)
{
await _dbConnection.DisposeAsync();
}
GC.SuppressFinalize(this);
}
/// <inheritdoc cref="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 void Dispose()
{
if (_dbConnection is null)
{
return;
}
_logger.LogDebug("Disposing database connection");
_dbConnection.Close();
_dbConnection.Dispose();
_dbConnection = null;
GC.SuppressFinalize(this);
}
}