src/Hx.IdentityServer.Extensions/ServiceExtensions/IHostServiceCollectionExtensions.cs
(完整代码) 2KBusing Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Polly;
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Extensions.Hosting
{
public static class IHostServiceCollectionExtensions
{
/// <summary>
/// 数据库迁移文件执行
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <param name="webHost"></param>
/// <param name="seeder"></param>
/// <returns></returns>
public static IHost MigrateDbContext<TContext>(this IHost webHost, Action<TContext, IServiceProvider> seeder) where TContext : DbContext
{
using (var scope = webHost.Services.CreateScope())
{
var services = scope.ServiceProvider;
var logger = services.GetRequiredService<ILogger<TContext>>();
var context = services.GetService<TContext>();
try
{
logger.LogInformation($"Migrating database associated with context {typeof(TContext).Name}");
var retry = Policy.Handle<Exception>()
.WaitAndRetry(new TimeSpan[]
{
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(15),
});
retry.Execute(() =>
{
context.Database.Migrate();
seeder(context, services);
});
logger.LogInformation($"Migrated database associated with context {typeof(TContext).Name}");
}
catch (Exception ex)
{
logger.LogError(ex, $"An error occurred while migrating the database used on context {typeof(TContext).Name}");
}
}
return webHost;
}
}
}
24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明
AI 解读
登录后可用,每次 10 积分,解读结果公开显示在下面。
还没有人解读过这个文件。
