How to use dotnet-ef tools with DI instanciated DbContext?

Viewed 49

I'm using a DDD approach and added a persistence layer to my project. The layer publishes an extension method to IServiceCollection which initializes efcore. I only publish repositories instead of the DbContext itself.

IServiceCollection Extension

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;
}

DbContext

internal sealed class AppDbContext: DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        :base(options)
    {
    }

    public DbSet<Book> Books { get; set; }
}

This works fine so far when using my app. But when I want to use the dotnet-ef tools the efcore wont be initialized because there is no startup project which calls the above extension method.

Is there a way to somehow work around this? I wish I just could pass the connectionstring from the CLI.

Migrations are also located in the persistence layer project if that matters.

What I've tried is to create a startup project which calls the extension method and then use the following command. But without success.

dotnet ef database update `
    --project .\src\Persistence\Persistence.csproj `
    --startup-project .\src\Persistence.Tools\Persistence.Tools.csproj `
    0

I keep getting the error message

Unable to create an object of type 'AppDbContext'.

1 Answers
Related