Get configuration in method CreateDbContext of IDesignTimeDbContextFactory in .NET 6.0 for GetConnectionString

Viewed 47

I need read the value connection string of appsettings.json for have this dynamic.

I have:

    public class StoreContextFactory : IDesignTimeDbContextFactory<StoreContext>
    {
        public StoreContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<StoreContext>();
            optionsBuilder.UseSqlServer(@"Server=localhost;Database=StoreCleanArchitecture;Trusted_Connection=True;");

            return new StoreContext(optionsBuilder.Options);
        }
    }

I need:

    public class StoreContextFactory : IDesignTimeDbContextFactory<StoreContext>
    {
        public StoreContext CreateDbContext(string[] args)
        {
            var defaultConnectionString = configuration.GetConnectionString("DefaultConnection");
            var optionsBuilder = new DbContextOptionsBuilder<StoreContext>();
            optionsBuilder.UseSqlServer(defaultConnectionString);

            return new StoreContext(optionsBuilder.Options);
        }
    }

Thx.

1 Answers

You can build configuration yourself via ConfigurationBuilder:

public class StoreContextFactory : IDesignTimeDbContextFactory<StoreContext>
{
    public StoreContext CreateDbContext(string[] args)
    {
        // add all needed configuration providers
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        var defaultConnectionString = configuration.GetConnectionString("DefaultConnection");
        var optionsBuilder = new DbContextOptionsBuilder<StoreContext>();
        optionsBuilder.UseSqlServer(defaultConnectionString);

        return new StoreContext(optionsBuilder.Options);
    }
}
Related