Skip to content

Commit 8fbd10c

Browse files
committed
Update admin project to use new IAliasServerDbContextFactory (#190)
1 parent 54d54f2 commit 8fbd10c

File tree

9 files changed

+148
-38
lines changed

9 files changed

+148
-38
lines changed

src/AliasVault.Admin/Main/Pages/MainBase.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,10 @@ public abstract class MainBase : OwningComponentBase
5656
protected AliasServerDbContext DbContext { get; set; } = null!;
5757

5858
/// <summary>
59-
/// Gets or sets the AliasServerDbContextFactory instance.
59+
/// Gets or sets the IAliasServerDbContextFactory instance.
6060
/// </summary>
6161
[Inject]
62-
protected IDbContextFactory<AliasServerDbContext> DbContextFactory { get; set; } = null!;
62+
protected IAliasServerDbContextFactory DbContextFactory { get; set; } = null!;
6363

6464
/// <summary>
6565
/// Gets or sets the GlobalLoadingService in order to manipulate the global loading spinner animation.

src/AliasVault.Admin/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
options.LoginPath = "/user/login";
7070
});
7171

72-
builder.Services.AddAliasVaultSqliteConfiguration();
72+
builder.Services.AddAliasVaultDatabaseConfiguration(builder.Configuration);
7373
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
7474
builder.Services.AddIdentityCore<AdminUser>(options =>
7575
{
@@ -133,7 +133,7 @@
133133
using (var scope = app.Services.CreateScope())
134134
{
135135
var container = scope.ServiceProvider;
136-
await using var db = await container.GetRequiredService<IDbContextFactory<AliasServerDbContext>>().CreateDbContextAsync();
136+
await using var db = container.GetRequiredService<IAliasServerDbContextFactory>().CreateDbContext();
137137
await db.Database.MigrateAsync();
138138

139139
await StartupTasks.CreateRolesIfNotExist(scope.ServiceProvider);

src/AliasVault.Admin/appsettings.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{
2+
"DatabaseProvider": "sqlite",
23
"ConnectionStrings": {
34
"AliasServerDbContext": "Data Source=../../database/AliasServerDb.sqlite"
45
},

src/Databases/AliasServerDb/AliasServerDbContext.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,20 @@ namespace AliasServerDb;
1818
/// we have two separate user objects, one for the admin panel and one for the vault. We manually
1919
/// define the Identity tables in the OnModelCreating method.
2020
/// </summary>
21-
public abstract class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyContext
21+
public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyContext
2222
{
2323
/// <summary>
2424
/// Initializes a new instance of the <see cref="AliasServerDbContext"/> class.
2525
/// </summary>
26-
protected AliasServerDbContext()
26+
public AliasServerDbContext()
2727
{
2828
}
2929

3030
/// <summary>
3131
/// Initializes a new instance of the <see cref="AliasServerDbContext"/> class.
3232
/// </summary>
3333
/// <param name="options">DbContextOptions.</param>
34-
protected AliasServerDbContext(DbContextOptions<AliasServerDbContext> options)
34+
public AliasServerDbContext(DbContextOptions<AliasServerDbContext> options)
3535
: base(options)
3636
{
3737
}

src/Databases/AliasServerDb/Configuration/DatabaseConfiguration.cs

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,6 @@
77

88
namespace AliasServerDb.Configuration;
99

10-
using System.Data.Common;
11-
using Microsoft.Data.Sqlite;
12-
using Microsoft.EntityFrameworkCore;
1310
using Microsoft.Extensions.Configuration;
1411
using Microsoft.Extensions.DependencyInjection;
1512

@@ -22,39 +19,29 @@ public static class DatabaseConfiguration
2219
/// Configures SQLite for use with Entity Framework Core.
2320
/// </summary>
2421
/// <param name="services">The IServiceCollection to add the DbContext to.</param>
22+
/// <param name="configuration">The IConfiguration to use for the connection string.</param>
2523
/// <returns>The IServiceCollection for method chaining.</returns>
26-
public static IServiceCollection AddAliasVaultSqliteConfiguration(this IServiceCollection services)
24+
public static IServiceCollection AddAliasVaultDatabaseConfiguration(this IServiceCollection services, IConfiguration configuration)
2725
{
28-
var serviceProvider = services.BuildServiceProvider();
29-
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
26+
var dbProvider = configuration.GetValue<string>("DatabaseProvider")?.ToLower() ?? "sqlite";
3027

31-
var connectionString = configuration.GetConnectionString("AliasServerDbContext");
32-
if (string.IsNullOrEmpty(connectionString))
28+
switch (dbProvider)
3329
{
34-
throw new InvalidOperationException("Connection string 'AliasServerDbContext' not found.");
30+
case "postgresql":
31+
services.AddScoped<IAliasServerDbContextFactory, PostgresqlDbContextFactory>();
32+
break;
33+
case "sqlite":
34+
default:
35+
services.AddScoped<IAliasServerDbContextFactory, SqliteDbContextFactory>();
36+
break;
3537
}
3638

37-
var sqliteConnectionStringBuilder = new SqliteConnectionStringBuilder(connectionString)
39+
services.AddScoped<AliasServerDbContext>(sp =>
3840
{
39-
Cache = SqliteCacheMode.Private,
40-
Mode = SqliteOpenMode.ReadWriteCreate,
41-
};
42-
43-
services.AddDbContextFactory<AliasServerDbContext>(options =>
44-
{
45-
options.UseSqlite(CreateAndConfigureSqliteConnection(sqliteConnectionStringBuilder.ConnectionString), sqliteOptions =>
46-
{
47-
sqliteOptions.CommandTimeout(60);
48-
}).UseLazyLoadingProxies();
41+
var factory = sp.GetRequiredService<IAliasServerDbContextFactory>();
42+
return factory.CreateDbContext();
4943
});
5044

5145
return services;
5246
}
53-
54-
private static SqliteConnection CreateAndConfigureSqliteConnection(string connectionString)
55-
{
56-
var connection = new SqliteConnection(connectionString);
57-
connection.Open();
58-
return connection;
59-
}
6047
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//-----------------------------------------------------------------------
2+
// <copyright file="IAliasServerDbContextFactory.cs" company="lanedirt">
3+
// Copyright (c) lanedirt. All rights reserved.
4+
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
5+
// </copyright>
6+
//-----------------------------------------------------------------------
7+
8+
namespace AliasServerDb;
9+
10+
/// <summary>
11+
/// The AliasServerDbContextFactory interface.
12+
/// </summary>
13+
public interface IAliasServerDbContextFactory
14+
{
15+
/// <summary>
16+
/// Creates a new AliasServerDbContext.
17+
/// </summary>
18+
/// <returns>The AliasServerDbContext.</returns>
19+
AliasServerDbContext CreateDbContext();
20+
21+
/// <summary>
22+
/// Creates a new AliasServerDbContext asynchronously.
23+
/// </summary>
24+
/// <param name="cancellationToken">The cancellation token.</param>
25+
/// <returns>A task that represents the asynchronous operation. The task result contains the AliasServerDbContext.</returns>
26+
Task<AliasServerDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default);
27+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//-----------------------------------------------------------------------
2+
// <copyright file="PostgresqlDbContextFactory.cs" company="lanedirt">
3+
// Copyright (c) lanedirt. All rights reserved.
4+
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
5+
// </copyright>
6+
//-----------------------------------------------------------------------
7+
8+
namespace AliasServerDb;
9+
10+
using Microsoft.EntityFrameworkCore;
11+
using Microsoft.Extensions.Configuration;
12+
13+
/// <summary>
14+
/// The AliasServerDbContextFactory interface.
15+
/// </summary>
16+
public class PostgresqlDbContextFactory : IAliasServerDbContextFactory
17+
{
18+
private readonly IConfiguration _configuration;
19+
20+
/// <summary>
21+
/// Initializes a new instance of the <see cref="PostgresqlDbContextFactory"/> class.
22+
/// </summary>
23+
/// <param name="configuration">The configuration.</param>
24+
public PostgresqlDbContextFactory(IConfiguration configuration)
25+
{
26+
_configuration = configuration;
27+
}
28+
29+
/// <inheritdoc/>
30+
public AliasServerDbContext CreateDbContext()
31+
{
32+
var optionsBuilder = new DbContextOptionsBuilder<AliasServerDbContext>();
33+
var connectionString = _configuration.GetConnectionString("AliasServerDbContext");
34+
35+
optionsBuilder
36+
.UseNpgsql(connectionString, options => options.CommandTimeout(60))
37+
.UseLazyLoadingProxies();
38+
39+
return new AliasServerDbContextPostgresql(optionsBuilder.Options);
40+
}
41+
42+
/// <inheritdoc/>
43+
public Task<AliasServerDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
44+
{
45+
return Task.FromResult(CreateDbContext());
46+
}
47+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//-----------------------------------------------------------------------
2+
// <copyright file="SqliteDbContextFactory.cs" company="lanedirt">
3+
// Copyright (c) lanedirt. All rights reserved.
4+
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
5+
// </copyright>
6+
//-----------------------------------------------------------------------
7+
8+
namespace AliasServerDb;
9+
10+
using Microsoft.EntityFrameworkCore;
11+
using Microsoft.Extensions.Configuration;
12+
13+
/// <summary>
14+
/// The AliasServerDbContextFactory interface.
15+
/// </summary>
16+
public class SqliteDbContextFactory : IAliasServerDbContextFactory
17+
{
18+
private readonly IConfiguration _configuration;
19+
20+
/// <summary>
21+
/// Initializes a new instance of the <see cref="SqliteDbContextFactory"/> class.
22+
/// </summary>
23+
/// <param name="configuration">The configuration.</param>
24+
public SqliteDbContextFactory(IConfiguration configuration)
25+
{
26+
_configuration = configuration;
27+
}
28+
29+
/// <inheritdoc/>
30+
public AliasServerDbContext CreateDbContext()
31+
{
32+
var optionsBuilder = new DbContextOptionsBuilder<AliasServerDbContext>();
33+
var connectionString = _configuration.GetConnectionString("AliasServerDbContext") +
34+
";Mode=ReadWriteCreate;Cache=Shared";
35+
36+
optionsBuilder
37+
.UseSqlite(connectionString, options => options.CommandTimeout(60))
38+
.UseLazyLoadingProxies();
39+
40+
return new AliasServerDbContextSqlite(optionsBuilder.Options);
41+
}
42+
43+
/// <inheritdoc/>
44+
public Task<AliasServerDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
45+
{
46+
return Task.FromResult(CreateDbContext());
47+
}
48+
}

src/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ namespace AliasVault.Shared.Server.Services;
2020
/// Server settings service.
2121
/// </summary>
2222
/// <param name="dbContextFactory">IDbContextFactory instance.</param>
23-
public class ServerSettingsService(IDbContextFactory<AliasServerDbContext> dbContextFactory)
23+
public class ServerSettingsService(IAliasServerDbContextFactory dbContextFactory)
2424
{
2525
private readonly Dictionary<string, string?> _cache = new();
2626

@@ -36,7 +36,7 @@ public class ServerSettingsService(IDbContextFactory<AliasServerDbContext> dbCon
3636
return cachedValue;
3737
}
3838

39-
await using var dbContext = await dbContextFactory.CreateDbContextAsync(CancellationToken.None);
39+
await using var dbContext = dbContextFactory.CreateDbContext();
4040
var setting = await dbContext.ServerSettings.FirstOrDefaultAsync(x => x.Key == key);
4141

4242
_cache[key] = setting?.Value;
@@ -57,7 +57,7 @@ public async Task SetSettingAsync(string key, string? value)
5757
return;
5858
}
5959

60-
await using var dbContext = await dbContextFactory.CreateDbContextAsync(CancellationToken.None);
60+
await using var dbContext = dbContextFactory.CreateDbContext();
6161
var setting = await dbContext.ServerSettings.FirstOrDefaultAsync(x => x.Key == key);
6262
var now = DateTime.UtcNow;
6363

@@ -96,7 +96,7 @@ public async Task SetSettingAsync(string key, string? value)
9696
/// <returns>The settings.</returns>
9797
public async Task<ServerSettingsModel> GetAllSettingsAsync()
9898
{
99-
await using var dbContext = await dbContextFactory.CreateDbContextAsync(CancellationToken.None);
99+
await using var dbContext = dbContextFactory.CreateDbContext();
100100
var settings = await dbContext.ServerSettings.ToDictionaryAsync(x => x.Key, x => x.Value);
101101

102102
// Create model with defaults

0 commit comments

Comments
 (0)