'EF Core Tools won't get options injected from ParameterStore using AWS SDK

I have a project deployed to AWS with Terraform that generates RDS credentials on deployment and saves them on AWS SystemsManager ParameterStore. For my startup script I have the settings mapped to options objects like this:

if (!builder.Environment.IsDevelopment())
  builder.Configuration
    .AddSystemsManager($"/{organizationName}/{applicationName}/{environmentName}", new AWSOptions
    {
      Region = RegionEndpoint.GetBySystemName(region)
    });

builder.Services.Configure<DatabaseOptions>(builder.Configuration.GetSection(DatabaseOptions.Section));

And then I create my DbContext for default and local environments like this:

if (!builder.Environment.IsDevelopment())
    builder.Services.AddDbContext<DataContext>();
else
    builder.Services.AddDbContext<DataContext, TestContext>();

The test context inherits from DataContext and overrides the configure method to use a local SQLite file, the actual context uses the PostgreSQL driver. Using these with EF Core tools I can generate migrations for other environments just fine like this:

dotnet ef migrations add InitialCreate --project API 
    --context DataContext --output-dir Migrations/Staging -- --environment staging

But when I try to apply these migrations using

dotnet ef database update/drop

commands, the configuration options won't get loaded into the objects like it does on runtime using AWSSdk. So the DatabaseOptions object will have every value null for staging/production environments if ran on local machine which throws this error:

'Failed creating connection: Couldn't set port (Parameter 'port')' on server 'Failed creating connection: Couldn't set port (Parameter 'port')'?

Is there any way to get around this without looking up the parameters terraform generated and pulling them down to hardcode in the appsettings files?



Solution 1:[1]

Solved using a custom factory implementing IDesignTimeDbContextFactory interface. Injected the custom options manually using Microsoft.Extensions.Configuration

Also have to run the commands with new options I manually parse in the factory method, because the factory method in another assembly won't respect launchSettings.json by default.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saegusae