Skip to content

Commit

Permalink
Configure ApplicationContextConfig.
Browse files Browse the repository at this point in the history
  • Loading branch information
TheTedder committed Oct 11, 2023
1 parent 44db85e commit 64d12c3
Showing 1 changed file with 36 additions and 22 deletions.
58 changes: 36 additions & 22 deletions LeaderboardBackend.Test/TestApi/TestApiFactory.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
Expand All @@ -11,6 +12,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Moq;
using Npgsql;
using Respawn;
Expand Down Expand Up @@ -46,31 +48,43 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
services.Remove(dbContextDescriptor);
}

PostgresConfig db = new()
{
Db = PostgresDatabaseFixture.Database!,
Port = (ushort)PostgresDatabaseFixture.Port,
Host = PostgresDatabaseFixture.PostgresContainer.Hostname,
User = PostgresDatabaseFixture.Username!,
Password = PostgresDatabaseFixture.Password!,
};

NpgsqlConnectionStringBuilder connectionBuilder = new()
{
Host = db.Host,
Username = db.User,
Password = db.Password,
Database = db.Db,
IncludeErrorDetail = true,
};

if (db.Port is not null)
{
connectionBuilder.Port = db.Port.Value;
}
services.Configure<ApplicationContextConfig>(conf =>
conf.Pg = new PostgresConfig
{
Db = PostgresDatabaseFixture.Database!,
Port = (ushort)PostgresDatabaseFixture.Port,
Host = PostgresDatabaseFixture.PostgresContainer.Hostname,
User = PostgresDatabaseFixture.Username!,
Password = PostgresDatabaseFixture.Password!
});

services.AddSingleton(container =>
{
ApplicationContextConfig appConfig = container
.GetRequiredService<IOptions<ApplicationContextConfig>>()
.Value;

if (appConfig.Pg is null)
{
throw new UnreachableException(
"The database configuration is invalid but it was not caught by validation!"
);
}

NpgsqlConnectionStringBuilder connectionBuilder = new()
{
Host = appConfig.Pg.Host,
Username = appConfig.Pg.User,
Password = appConfig.Pg.Password,
Database = appConfig.Pg.Db,
IncludeErrorDetail = true,
};

if (appConfig.Pg.Port is not null)
{
connectionBuilder.Port = appConfig.Pg.Port.Value;
}

NpgsqlDataSourceBuilder dataSourceBuilder = new(connectionBuilder.ConnectionString);
dataSourceBuilder.UseNodaTime().MapEnum<UserRole>();
return dataSourceBuilder.Build();
Expand Down

0 comments on commit 64d12c3

Please sign in to comment.