c# - 使用我的类库中的代码运行迁移
问题描述
我有一个类库,稍后将打包为 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,因为它是一个类库。
那么,如何从我的类库运行我的迁移?
解决方案
在单独的应用程序中创建数据库迁移,而不是在您拥有业务逻辑的应用程序中。此迁移应用程序可以在部署应用程序时作为部署管道的一部分运行。
我不会使用诸如数据库迁移之类的东西来加载应用程序的启动。
推荐阅读
- postgresql - psql 服务器 ssh 隧道身份验证失败
- python - 计算其他类值的最小值后如何获取类方法的值
- go - 如何在 computeService.Zones.List(project) Google Cloud Platform API 中添加过滤器
- apache-kafka - Apache Kafka Consumer 在 1 个主题上消耗数千个主题与数千个分区
- javascript - 使用 Node JS 在文本文件的第一行和最后一行添加花括号?
- linux - 如何阅读直到分隔符?
- python - 如何从交互式解释器调用函数并为 argparse 传递参数?
- javascript - 从 Dart 转换为 Javascript 时,Dart2JS 无法运行异步代码
- php - 选择查询执行两次
- java - 如何解决这个“不使用 PreparedStatement 方法”的问题?