fix: migrate to IDbContextFactory and remove direct AppDbContext from DI (#11)

Reviewed-on: #11
Co-authored-by: Marek Jasiński <jasins.marek@gmail.com>
Co-committed-by: Marek Jasiński <jasins.marek@gmail.com>
This commit was merged in pull request #11.
This commit is contained in:
2026-05-07 16:39:21 +00:00
committed by Marek Jaisński
parent 3faecbb639
commit 2248a2b757
35 changed files with 983 additions and 215 deletions
@@ -0,0 +1,113 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using NexusReader.Domain.Entities;
namespace NexusReader.Data.Persistence;
public class AppDbContext : IdentityDbContext<NexusUser>
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
// Suppress the pending model changes warning to avoid runtime exceptions in some environments
optionsBuilder.ConfigureWarnings(w => w.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.RelationalEventId.PendingModelChangesWarning));
}
public DbSet<SemanticKnowledgeCache> SemanticKnowledgeCache => Set<SemanticKnowledgeCache>();
public DbSet<KnowledgeUnit> KnowledgeUnits => Set<KnowledgeUnit>();
public DbSet<KnowledgeUnitLink> KnowledgeUnitLinks => Set<KnowledgeUnitLink>();
public DbSet<Ebook> Ebooks => Set<Ebook>();
public DbSet<QuizResult> QuizResults => Set<QuizResult>();
public DbSet<SubscriptionPlan> SubscriptionPlans => Set<SubscriptionPlan>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasPostgresExtension("vector");
modelBuilder.Entity<NexusUser>(entity =>
{
entity.Property(u => u.LastReadPageId).HasMaxLength(255);
entity.Property(u => u.LastReadAt).IsRequired(false);
entity.HasIndex(u => u.TenantId);
entity.HasOne(u => u.SubscriptionPlan)
.WithMany()
.HasForeignKey(u => u.SubscriptionPlanId)
.OnDelete(DeleteBehavior.Restrict);
// Note: DefaultValue for int is 1 (which corresponds to 'Free' in our seed)
entity.Property(u => u.SubscriptionPlanId)
.HasDefaultValue(1);
});
modelBuilder.Entity<SubscriptionPlan>(entity =>
{
entity.HasIndex(p => p.PlanName).IsUnique();
});
modelBuilder.Entity<SemanticKnowledgeCache>(entity =>
{
entity.HasKey(e => e.ContentHash);
entity.HasIndex(e => e.ContentHash).IsUnique();
entity.HasIndex(e => e.TenantId);
entity.Property(e => e.Vector).HasColumnType("vector(1536)");
});
modelBuilder.Entity<KnowledgeUnit>(entity =>
{
entity.HasKey(e => e.Id);
entity.HasIndex(e => e.TenantId);
entity.HasIndex(e => e.SourceId);
entity.Property(e => e.Vector).HasColumnType("vector(768)");
});
modelBuilder.Entity<KnowledgeUnitLink>(entity =>
{
entity.HasKey(e => e.Id);
entity.HasOne(e => e.SourceUnit)
.WithMany(u => u.OutgoingLinks)
.HasForeignKey(e => e.SourceUnitId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(e => e.TargetUnit)
.WithMany(u => u.IncomingLinks)
.HasForeignKey(e => e.TargetUnitId)
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<Ebook>(entity =>
{
entity.HasOne(e => e.User)
.WithMany(u => u.Ebooks)
.HasForeignKey(e => e.UserId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasIndex(e => e.TenantId);
});
modelBuilder.Entity<QuizResult>(entity =>
{
entity.HasOne(e => e.User)
.WithMany(u => u.QuizResults)
.HasForeignKey(e => e.UserId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasIndex(e => e.TenantId);
});
// Seed Subscription Plans with deterministic IDs
modelBuilder.Entity<SubscriptionPlan>().HasData(
new SubscriptionPlan { Id = 1, PlanName = SubscriptionPlan.FreeName, AITokenLimit = 5000, IsUnlimitedTokens = false, MonthlyPrice = 0m, StripeProductId = "prod_Free789" },
new SubscriptionPlan { Id = 2, PlanName = SubscriptionPlan.BasicName, AITokenLimit = 10000, IsUnlimitedTokens = false, MonthlyPrice = 9.99m, StripeProductId = "prod_basic_placeholder" },
new SubscriptionPlan { Id = 3, PlanName = SubscriptionPlan.ProName, AITokenLimit = 50000, IsUnlimitedTokens = false, MonthlyPrice = 19.99m, StripeProductId = "prod_pro_placeholder" },
new SubscriptionPlan { Id = 4, PlanName = SubscriptionPlan.EnterpriseName, AITokenLimit = 1000000000, IsUnlimitedTokens = true, MonthlyPrice = 99.99m, StripeProductId = "prod_enterprise_placeholder" }
);
}
}
@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Pgvector.EntityFrameworkCore;
namespace NexusReader.Data.Persistence;
public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
// Try to find the Web project directory by looking for the solution root
var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory());
while (currentDir != null && !File.Exists(Path.Combine(currentDir.FullName, "NexusReader.slnx")))
{
currentDir = currentDir.Parent;
}
var basePath = currentDir != null
? Path.Combine(currentDir.FullName, "src", "NexusReader.Web.New")
: Directory.GetCurrentDirectory();
var configuration = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json", optional: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true)
.AddEnvironmentVariables()
.Build();
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
var connectionString = configuration.GetConnectionString("PostgresConnection");
if (string.IsNullOrEmpty(connectionString))
{
// For design time, if no PG connection is found, we might be using Sqlite or just testing
connectionString = "Host=localhost;Database=nexus_reader;Username=postgres;Password=postgres";
}
optionsBuilder.UseNpgsql(connectionString, x => x.UseVector());
return new AppDbContext(optionsBuilder.Options);
}
}
@@ -0,0 +1,92 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using NexusReader.Domain.Entities;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace NexusReader.Data.Persistence;
public static class DbInitializer
{
public static async Task SeedAsync(IServiceProvider serviceProvider)
{
using var scope = serviceProvider.CreateScope();
var passwordHasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher<NexusUser>>();
var dbContextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AppDbContext>>();
using var dbContext = await dbContextFactory.CreateDbContextAsync();
try
{
Console.WriteLine("[Seeder] Starting database seeding...");
// Seed Subscription Plans
if (!dbContext.SubscriptionPlans.Any())
{
dbContext.SubscriptionPlans.AddRange(new List<SubscriptionPlan>
{
new SubscriptionPlan { Id = SubscriptionPlan.FreeId, PlanName = SubscriptionPlan.FreeName, AITokenLimit = 5000, IsUnlimitedTokens = false, MonthlyPrice = 0, StripeProductId = "prod_Free789" },
new SubscriptionPlan { Id = SubscriptionPlan.ProId, PlanName = SubscriptionPlan.ProName, AITokenLimit = 50000, IsUnlimitedTokens = false, MonthlyPrice = 19, StripeProductId = "prod_Pro123" },
new SubscriptionPlan { Id = SubscriptionPlan.EnterpriseId, PlanName = SubscriptionPlan.EnterpriseName, AITokenLimit = 1000000000, IsUnlimitedTokens = true, MonthlyPrice = 99, StripeProductId = "prod_Enterprise456" }
});
await dbContext.SaveChangesAsync();
Console.WriteLine("[Seeder] Subscription plans seeded.");
}
// Seed Roles
string[] roleNames = { "Admin", "User" };
foreach (var roleName in roleNames)
{
var roleExist = dbContext.Roles.Any(r => r.Name == roleName);
if (!roleExist)
{
dbContext.Roles.Add(new IdentityRole { Name = roleName, NormalizedName = roleName.ToUpper() });
Console.WriteLine($"[Seeder] Created role: {roleName}");
}
}
await dbContext.SaveChangesAsync();
// Seed Admin User
var adminEmail = "admin@nexus.com";
var normalizedEmail = adminEmail.ToUpper();
var adminUser = await dbContext.Users.FirstOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail);
if (adminUser == null)
{
adminUser = new NexusUser
{
UserName = adminEmail,
NormalizedUserName = normalizedEmail,
Email = adminEmail,
NormalizedEmail = normalizedEmail,
EmailConfirmed = true,
SubscriptionPlanId = SubscriptionPlan.EnterpriseId,
AITokenLimit = 1000000,
TenantId = Guid.NewGuid().ToString(),
SecurityStamp = Guid.NewGuid().ToString()
};
adminUser.PasswordHash = passwordHasher.HashPassword(adminUser, "Admin123!");
dbContext.Users.Add(adminUser);
await dbContext.SaveChangesAsync();
var adminRole = await dbContext.Roles.FirstAsync(r => r.Name == "Admin");
dbContext.UserRoles.Add(new IdentityUserRole<string> { UserId = adminUser.Id, RoleId = adminRole.Id });
await dbContext.SaveChangesAsync();
Console.WriteLine($"[Seeder] Admin user created successfully: {adminEmail}");
}
else
{
Console.WriteLine("[Seeder] Admin user already exists.");
}
}
catch (Exception ex)
{
Console.WriteLine($"[Seeder] Critical error during seeding: {ex.Message}");
}
}
}