2026-05-21 15:52:36 +08:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
|
2026-05-22 14:29:22 +08:00
|
|
|
|
namespace FileShare_EFCore.Database
|
2026-05-21 15:52:36 +08:00
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 数据库提供程序注册表 —— 统一注册所有支持的提供程序配置委托。
|
|
|
|
|
|
/// 具体使用哪个提供程序由各宿主项目决定:
|
2026-05-22 14:29:22 +08:00
|
|
|
|
/// FileShare-API:从 appsettings.json 的 DatabaseConfiguration 节读取;
|
|
|
|
|
|
/// FileShare-PC :固定使用 SQLite。
|
2026-05-21 15:52:36 +08:00
|
|
|
|
/// </summary>
|
|
|
|
|
|
public static class DatabaseProviderRegistry
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 提供程序配置委托:optionsBuilder, connectionString, timeout → void
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public delegate void ProviderConfigurator(DbContextOptionsBuilder optionsBuilder, string connectionString, int timeout);
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 保存已注册的数据库提供程序及其配置委托。
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
private static readonly Dictionary<DatabaseProvider, ProviderConfigurator> _providers = new();
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 注册一个数据库提供程序。
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public static void Register(DatabaseProvider provider, ProviderConfigurator configurator)
|
|
|
|
|
|
{
|
|
|
|
|
|
_providers[provider] = configurator;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 尝试获取注册的提供程序配置。
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public static bool TryGet(DatabaseProvider provider, out ProviderConfigurator configurator)
|
|
|
|
|
|
{
|
|
|
|
|
|
return _providers.TryGetValue(provider, out configurator!);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
2026-05-22 14:29:22 +08:00
|
|
|
|
/// 注册所有内置提供程序的默认配置(四个包均已内置在 FileShare-EFCore 中)。
|
2026-05-21 15:52:36 +08:00
|
|
|
|
/// 注册完成后由调用方根据自身需求选择具体的 <see cref="DatabaseProvider"/>。
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public static void RegisterDefaults()
|
|
|
|
|
|
{
|
|
|
|
|
|
Register(DatabaseProvider.SQLite, (opts, cs, timeout) =>
|
|
|
|
|
|
opts.UseSqlite(cs, o => o.CommandTimeout(timeout)));
|
|
|
|
|
|
|
|
|
|
|
|
Register(DatabaseProvider.SqlServer, (opts, cs, timeout) =>
|
|
|
|
|
|
opts.UseSqlServer(cs, o => { o.CommandTimeout(timeout); o.EnableRetryOnFailure(3); }));
|
|
|
|
|
|
|
|
|
|
|
|
Register(DatabaseProvider.PostgreSQL, (opts, cs, timeout) =>
|
|
|
|
|
|
opts.UseNpgsql(cs, o => { o.CommandTimeout(timeout); o.EnableRetryOnFailure(3); }));
|
|
|
|
|
|
|
|
|
|
|
|
Register(DatabaseProvider.MySQL, (opts, cs, timeout) =>
|
|
|
|
|
|
opts.UseMySQL(cs, o => o.CommandTimeout(timeout)));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|