首页 > 解决方案 > 使用我的类库中的代码运行迁移

问题描述

我有一个类库,稍后将打包为 nuget 包。

要使用我的 nuget 包,我在库中名为 Injections.cs 的文件中有一个方法,您可以将其添加到您的 startup.cs 文件中。

它看起来像这样:

public static class Injections
{
    public static IServiceCollection AddServiceAndRoleSecurity(this IServiceCollection services)
    {
        services.AddTransient<ISecurityService, SecurityService>();
        services.AddTransient<IDatabaseContextFactory, DatabaseContextFactory>();
        services.AddTransient<ISecurityRepository, SecurityRepository>();

        services.AddDbContext<IDatabaseContext, DatabaseContext>(options =>
            options.UseSqlServer(@""",
            x => x.MigrationsAssembly(typeof(DatabaseContext).Assembly.FullName)));

        services.AddMemoryCache();

        return services;
    }
}

因此,如果您有一个想要使用 nuget 包的项目,则必须services.AddServiceAndRoleSecurity()在您的 startup.cs中添加

我遇到的问题是在我的 Injections.cs 中,如果有任何新脚本,我想运行迁移脚本。我偶然发现了以下代码片段:

public static IApplicationBuilder CreateDatabase(this IApplicationBuilder app, IServiceScopeFactory scopeFactory)
{
    using (var scope = scopeFactory.CreateScope())
    {
        var db = scope.ServiceProvider.GetRequiredService<IDatabaseContext>();

        var migrations = db.DatabaseAccessor.GetPendingMigrations();

        if (migrations.Any())
            db.DatabaseAccessor.Migrate();
    }

    return app;
}

但是你通常会在你有一个 Startup.cs 文件的地方找到这种类型的解决方案,但在我的例子中,我没有任何 Startup.cs,因为它是一个类库。

那么,如何从我的类库运行我的迁移?

标签: c#asp.net-core.net-core

解决方案


在单独的应用程序中创建数据库迁移,而不是在您拥有业务逻辑的应用程序中。此迁移应用程序可以在部署应用程序时作为部署管道的一部分运行。

我不会使用诸如数据库迁移之类的东西来加载应用程序的启动。


推荐阅读