.net . Net6中的IHost扩展

nle07wnf  于 2022-12-30  发布在  .NET
关注(0)|答案(2)|浏览(150)

我正在尝试将EF Seed迁移的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();
        }
z31licg0

z31licg01#

迁移数据库:

public static void MigrateDatabase(this IServiceProvider sp)
{
    var loggerFactory = sp.GetRequiredService<ILoggerFactory>();

    // operations
}

程序:

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.Services.MigrateDatabase();

apo.Run();
wvyml7n5

wvyml7n52#

在Program.cs中这样使用:)

var app = builder.Build();
 app.MigrateDatabase<WebSocketAcceptContext>();

相关问题