Base solution for your next web application
Open Closed

Access appsettings.json in DbContext #9492


User avatar
0
compassinformatics17 created

Hi All, I am trying to access some Azure specific settings in my DbContext. It works in local dev but fails once deployed to Azure or IIS becuase WebContentDirectoryFinder.CalculateContentRootFolder() is apparently for Dev.

I am trying to configure Azure Managed Identity access and I need to edit my context as follows.

public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
            // Check to see if we are attempting to connect to an Azure DB. If we are use Azure Managed Identity to authenticate.
            var dbConnection = Database.GetDbConnection();
            if (dbConnection is SqlConnection connection)
            {
                // If not an Azure db connection, just return, no need to get managed identity token.
                if (!connection.ConnectionString.Contains(_appConfiguration["Azure:azureDatabaseEndpoint"], StringComparison.OrdinalIgnoreCase))
                    return;

                // If an Azure connection but using password, just return, no need to get managed identity token.
                if (connection.ConnectionString.Contains("password=", StringComparison.OrdinalIgnoreCase))
                    return;

                // Get Azure managed identity token for the given AzureServiceTokenProviderConnectionString connection string.
                // https://docs.microsoft.com/en-us/azure/key-vault/general/service-to-service-authentication#connection-string-support
                connection.AccessToken = new AzureServiceTokenProvider(_appConfiguration["Azure:AzureServiceTokenProviderConnectionString"])
                    .GetAccessTokenAsync($"https://{_appConfiguration["Azure:AzureDatabaseEndpoint"]}/")
                    .Result;
            }
        }

I could use DI to pull in IAppConfigurationAccessor as one would normally do but this then causes issues because the framework is designed to use the normal constructor

public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)

I also tried to get them locally in the context as follows, which works in Dev but not on IIS or Azure because of WebContentDirectoryFinder.CalculateContentRootFolder() being Dev only functionality.

// Enable access appsettings.json in the context.
private readonly IConfigurationRoot _appConfiguration = AppConfigurations.Get(
                                                                    WebContentDirectoryFinder.CalculateContentRootFolder(),
                                                                    addUserSecrets: true
                                                                    );

Is there some way in which I can access the appsettings.json from within the context other than this or is there a way for me to get the correct path for the root directory of MVC?

Thanks, Barry.


2 Answer(s)
  • User Avatar
    0
    compassinformatics17 created

    Hi Guys, I managed to get this sorted. This allows you to access appsettings.json from the context.

    // Enable access appsettings.json in the context.
    private readonly IConfigurationRoot _appConfiguration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .Build();
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    @compassinformatics17 Thanks :)