-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use DatabaseConnectionManager to manage connections
- Loading branch information
Showing
3 changed files
with
67 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Threading.Tasks; | ||
using Microsoft.Extensions.Configuration; | ||
using Npgsql; | ||
|
||
namespace OoLunar.Tomoe.Database | ||
{ | ||
public sealed class DatabaseConnectionManager : IAsyncDisposable, IDisposable | ||
{ | ||
private readonly List<NpgsqlConnection> _connections = []; | ||
private readonly string _connectionString; | ||
|
||
public DatabaseConnectionManager(IConfiguration configuration) | ||
{ | ||
ArgumentNullException.ThrowIfNull(configuration, nameof(configuration)); | ||
_connectionString = new NpgsqlConnectionStringBuilder() | ||
{ | ||
Host = configuration.GetValue("database:host", "localhost"), | ||
Port = configuration.GetValue("database:port", 5432), | ||
Username = configuration.GetValue("database:username", "postgres"), | ||
Password = configuration.GetValue("database:password", "postgres"), | ||
Database = configuration.GetValue("database:database", "tomoe"), | ||
CommandTimeout = configuration.GetValue("database:timeout", 5), | ||
#if DEBUG | ||
IncludeErrorDetail = true | ||
#endif | ||
}.ConnectionString; | ||
} | ||
|
||
public NpgsqlConnection GetConnection() | ||
{ | ||
NpgsqlConnection connection = new(_connectionString); | ||
_connections.Add(connection); | ||
return connection; | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
foreach (NpgsqlConnection connection in _connections) | ||
{ | ||
connection.Dispose(); | ||
} | ||
} | ||
|
||
public async ValueTask DisposeAsync() | ||
{ | ||
foreach (NpgsqlConnection connection in _connections) | ||
{ | ||
await connection.DisposeAsync(); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters