70 lines
2.3 KiB
C#
70 lines
2.3 KiB
C#
using Npgsql;
|
|
using PlanTempus.Database.ModuleRegistry;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace PlanTempus.Database.Core.ConnectionFactory
|
|
{
|
|
public class PostgresConnectionFactory : IDbConnectionFactory, IAsyncDisposable
|
|
{
|
|
private readonly NpgsqlDataSource _baseDataSource;
|
|
private readonly Action<NpgsqlDataSourceBuilder> _configureDataSource;
|
|
private readonly Microsoft.Extensions.Logging.ILoggerFactory _loggerFactory;
|
|
|
|
public PostgresConnectionFactory(
|
|
string connectionString,
|
|
Microsoft.Extensions.Logging.ILoggerFactory loggerFactory = null,
|
|
Action<NpgsqlDataSourceBuilder> configureDataSource = null)
|
|
{
|
|
_loggerFactory = loggerFactory;
|
|
_configureDataSource = configureDataSource ?? (builder => { });
|
|
|
|
// Opret base data source med konfiguration
|
|
var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
|
|
ConfigureDataSourceBuilder(dataSourceBuilder);
|
|
_baseDataSource = dataSourceBuilder.Build();
|
|
}
|
|
|
|
public IDbConnection Create()
|
|
{
|
|
return _baseDataSource.CreateConnection();
|
|
}
|
|
|
|
public IDbConnection Create(string username, string password)
|
|
{
|
|
var connectionStringBuilder = new NpgsqlConnectionStringBuilder(
|
|
_baseDataSource.ConnectionString)
|
|
{
|
|
Username = username,
|
|
Password = password
|
|
};
|
|
|
|
var tempDataSourceBuilder = new NpgsqlDataSourceBuilder(
|
|
connectionStringBuilder.ToString());
|
|
|
|
ConfigureDataSourceBuilder(tempDataSourceBuilder);
|
|
|
|
var tempDataSource = tempDataSourceBuilder.Build();
|
|
return tempDataSource.CreateConnection();
|
|
}
|
|
|
|
private void ConfigureDataSourceBuilder(NpgsqlDataSourceBuilder builder)
|
|
{
|
|
if (_loggerFactory != null)
|
|
{
|
|
builder.UseLoggerFactory(_loggerFactory);
|
|
}
|
|
|
|
_configureDataSource?.Invoke(builder);
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await _baseDataSource.DisposeAsync();
|
|
}
|
|
}
|
|
}
|