.Net6 中的 IHost 扩展
IHost extension in .Net6
我正在尝试将用于 EF 种子迁移的 IHost 扩展从 .Net5 迁移到 .Net6。能否请您指导我进行此转换的正确方法。
public static class HostExtensions
{
public static IHost MigrateDatabase<TContext>(this IHost host,
Action<TContext, IServiceProvider> seeder,
int? retry = 0) where TContext : DbContext
{
int retryForAvailability = retry.Value;
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
<code removed for brevity>
}
return host;
}
}
扩展在 .Net5 中调用如下:
public static void Main(string[] args)
{
CreateHostBuilder(args)
.Build()
.MigrateDatabase<OrderContext>((context, services) =>
{
var logger = services.GetService<ILogger<OrderContextSeed>>();
OrderContextSeed
.SeedAsync(context, logger)
.Wait();
})
.Run();
}
迁移数据库:
public static IHost MigrateDatabase(this IHost host)
{
using var scope = host.Services.CreateScope();
var sp = scope.ServiceProvider;
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
// operations
return host;
}
Program.cs :
var builder = WebApplication.CreateBuilder(args);
builder.Host
.Build()
.MigrateDatabase();
var app = builder.Build();
apo.Run();
我正在尝试将用于 EF 种子迁移的 IHost 扩展从 .Net5 迁移到 .Net6。能否请您指导我进行此转换的正确方法。
public static class HostExtensions
{
public static IHost MigrateDatabase<TContext>(this IHost host,
Action<TContext, IServiceProvider> seeder,
int? retry = 0) where TContext : DbContext
{
int retryForAvailability = retry.Value;
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
<code removed for brevity>
}
return host;
}
}
扩展在 .Net5 中调用如下:
public static void Main(string[] args)
{
CreateHostBuilder(args)
.Build()
.MigrateDatabase<OrderContext>((context, services) =>
{
var logger = services.GetService<ILogger<OrderContextSeed>>();
OrderContextSeed
.SeedAsync(context, logger)
.Wait();
})
.Run();
}
迁移数据库:
public static IHost MigrateDatabase(this IHost host)
{
using var scope = host.Services.CreateScope();
var sp = scope.ServiceProvider;
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
// operations
return host;
}
Program.cs :
var builder = WebApplication.CreateBuilder(args);
builder.Host
.Build()
.MigrateDatabase();
var app = builder.Build();
apo.Run();