【发布时间】:2021-06-07 21:47:26
【问题描述】:
我正在使用 DDD 方法并在我的项目中添加了一个持久层。该层向IServiceCollection 发布了一个扩展方法,用于初始化efcore。我只发布存储库而不是 DbContext 本身。
IServiceCollection 扩展
public static IServiceCollection AddPersistenceLayer(this IServiceCollection services, string connectionString)
{
// internal dependencies
services.AddDbContextFactory<AppDbContext>(
o => o.UseSqlServer(connectionString, p => p.EnableRetryOnFailure()));
services.AddDbContext<AppDbContext>(
o => o.UseSqlServer(connectionString, p => p.EnableRetryOnFailure()));
// public dependencies (consument of DbContext)
services.AddTransient<IBookRepository, BookRepository>();
return services;
}
数据库上下文
internal sealed class AppDbContext: DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
:base(options)
{
}
public DbSet<Book> Books { get; set; }
}
到目前为止,在使用我的应用程序时效果很好。但是当我想使用dotnet-ef工具时,efcore不会被初始化,因为没有调用上述扩展方法的启动项目。
有没有办法解决这个问题?我希望我可以从 CLI 传递连接字符串。
如果重要,迁移也位于持久层项目中。
我尝试的是创建一个调用扩展方法的启动项目,然后使用以下命令。但没有成功。
dotnet ef database update `
--project .\src\Persistence\Persistence.csproj `
--startup-project .\src\Persistence.Tools\Persistence.Tools.csproj `
0
我不断收到错误消息
无法创建“AppDbContext”类型的对象。
【问题讨论】:
标签: c# entity-framework-core domain-driven-design ddd-repositories