Setting up a db factory with logging
Important so we can log all commands
This commit is contained in:
parent
ad4ed12f00
commit
1501ff442a
10 changed files with 412 additions and 177 deletions
70
Database/Core/ConnectionFactory/Class1.cs
Normal file
70
Database/Core/ConnectionFactory/Class1.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue