feat: 扩展领域模型与配置
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
using TakeoutSaaS.Infrastructure.Common.Persistence;
|
||||
using TakeoutSaaS.Shared.Abstractions.Security;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.Common.Persistence.DesignTime;
|
||||
|
||||
/// <summary>
|
||||
/// EF Core 设计时 DbContext 工厂基类,提供统一的连接串与依赖替身。
|
||||
/// </summary>
|
||||
internal abstract class DesignTimeDbContextFactoryBase<TContext> : IDesignTimeDbContextFactory<TContext>
|
||||
where TContext : TenantAwareDbContext
|
||||
{
|
||||
private readonly string _connectionStringEnvVar;
|
||||
private readonly string _defaultDatabase;
|
||||
|
||||
protected DesignTimeDbContextFactoryBase(string connectionStringEnvVar, string defaultDatabase)
|
||||
{
|
||||
_connectionStringEnvVar = connectionStringEnvVar;
|
||||
_defaultDatabase = defaultDatabase;
|
||||
}
|
||||
|
||||
public TContext CreateDbContext(string[] args)
|
||||
{
|
||||
var optionsBuilder = new DbContextOptionsBuilder<TContext>();
|
||||
optionsBuilder.UseNpgsql(
|
||||
ResolveConnectionString(),
|
||||
npgsql =>
|
||||
{
|
||||
npgsql.CommandTimeout(30);
|
||||
npgsql.EnableRetryOnFailure();
|
||||
});
|
||||
|
||||
return CreateContext(
|
||||
optionsBuilder.Options,
|
||||
new DesignTimeTenantProvider(),
|
||||
new DesignTimeCurrentUserAccessor());
|
||||
}
|
||||
|
||||
protected abstract TContext CreateContext(
|
||||
DbContextOptions<TContext> options,
|
||||
ITenantProvider tenantProvider,
|
||||
ICurrentUserAccessor currentUserAccessor);
|
||||
|
||||
private string ResolveConnectionString()
|
||||
{
|
||||
var env = Environment.GetEnvironmentVariable(_connectionStringEnvVar);
|
||||
if (!string.IsNullOrWhiteSpace(env))
|
||||
{
|
||||
return env;
|
||||
}
|
||||
|
||||
return $"Host=localhost;Port=5432;Database={_defaultDatabase};Username=postgres;Password=postgres";
|
||||
}
|
||||
|
||||
private sealed class DesignTimeTenantProvider : ITenantProvider
|
||||
{
|
||||
public Guid GetCurrentTenantId() => Guid.Empty;
|
||||
}
|
||||
|
||||
private sealed class DesignTimeCurrentUserAccessor : ICurrentUserAccessor
|
||||
{
|
||||
public Guid UserId => Guid.Empty;
|
||||
public bool IsAuthenticated => false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user