Skip to content

Commit

Permalink
- update DbContextOptionsBuilderExtensions
Browse files Browse the repository at this point in the history
  • Loading branch information
ArdenHide committed Nov 14, 2023
1 parent b53058d commit ed81801
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,36 +1,47 @@
using SecretsManager;
using EnvironmentManager;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations.Internal;

namespace ConfiguredSqlConnection.Extensions;

public static class DbContextOptionsBuilderExtensions
{
private static readonly EnvManager envManager = new();

public static DbContextOptionsBuilder ConfigureFromActionConnection(this DbContextOptionsBuilder optionsBuilder)
public static DbContextOptionsBuilder ConfigureFromActionConnection(this DbContextOptionsBuilder optionsBuilder, string? migrationsAssembly = null)
{
if (optionsBuilder.IsConfigured) return optionsBuilder;

var connectionString = envManager.GetEnvironmentValue<string>("CONFIGUREDSQLCONNECTION_ACTION_CONNECTION");
if (!string.IsNullOrEmpty(connectionString))
if (string.IsNullOrEmpty(connectionString)) return optionsBuilder;

if (string.IsNullOrWhiteSpace(migrationsAssembly))
{
optionsBuilder.UseSqlServer(connectionString);
}
else
{
optionsBuilder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly));
}

return optionsBuilder;
}

public static DbContextOptionsBuilder ConfigureFromSecretConnection(this DbContextOptionsBuilder optionsBuilder)
public static DbContextOptionsBuilder ConfigureFromSecretConnection(this DbContextOptionsBuilder optionsBuilder, string? migrationsAssembly = null)
{
if (optionsBuilder.IsConfigured) return optionsBuilder;

var secretValue = envManager.GetEnvironmentValue<string>("CONFIGUREDSQLCONNECTION_SECRET_NAME_OF_CONNECTION", true);
var connectionString = new SecretManager().GetSecretValue(secretValue, "connectionString");
if (!string.IsNullOrEmpty(connectionString))
if (string.IsNullOrEmpty(connectionString)) return optionsBuilder;

if (string.IsNullOrWhiteSpace(migrationsAssembly))
{
optionsBuilder.UseSqlServer(connectionString);
}
else
{
optionsBuilder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly));
}

return optionsBuilder;
}
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ optionsBuilder
optionsBuilder
.ConfigureFromSecretConnection();

// Try to configure action connection also try to configure db connection via SecretManager.
optionsBuilder
.ConfigureFromActionConnection()
.ConfigureFromSecretConnection();

// Try to configure action connection also try to configure db connection via SecretManager.
optionsBuilder
.ConfigureFromActionConnection()
Expand Down

0 comments on commit ed81801

Please sign in to comment.