60 lines
2.4 KiB
C#
60 lines
2.4 KiB
C#
using Microsoft.EntityFrameworkCore;
|
||
|
||
namespace FileShare_EFCore.Database
|
||
{
|
||
/// <summary>
|
||
/// 数据库提供程序注册表 —— 统一注册所有支持的提供程序配置委托。
|
||
/// 具体使用哪个提供程序由各宿主项目决定:
|
||
/// FileShare-API:从 appsettings.json 的 DatabaseConfiguration 节读取;
|
||
/// FileShare-PC :固定使用 SQLite。
|
||
/// </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>
|
||
/// 注册所有内置提供程序的默认配置(四个包均已内置在 FileShare-EFCore 中)。
|
||
/// 注册完成后由调用方根据自身需求选择具体的 <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)));
|
||
}
|
||
}
|
||
}
|
||
|