Search code examples
c#entity-frameworkazureazure-keyvaultn-layer

Azure Key Vault Connection Strings and N-Layered Design


This question relates to the following post which maybe helpful: Azure DevOps CI/CD and Separating Connection Strings from Source Control

I'm currently working on an N-Layered project based off of an article by Imar Spaanjaars named ASP.NET N-Layered Applications

I'm trying to implement Azure Key Vault to, I guess you can say, abstract secrets from the application itself.

Goal

I want implement Azure Key Vault using this N-Tier concept. I have a sample project located at NLayer-Spaanjaars.ContactManager

Problem

I'm try to figure out how to use Key Vault Syntax Reference to properly retrieve the secret(s) (connection string) with Entity Framework.

Update 2019/2/22

As stated in the comments, I'm trying to find out how to inject or override the connection string at runtime with values for the Key Vault on a non-Core .Net Web API app.


Solution

  • I managed to get this working by modifying my DbContext like so:

    public class MyContext : BaseDataContext {
        public MyContext()
                : this(GetDbConnection()) {
        }
    
        public MyContext(string connectionString)
                : base(connectionString) {
        }
    
        public static string GetDbConnection() {
            // Get the value from the AppSettings section in the Web.config file that will be updated by Key Vault
            var connectionString = ConfigurationManager.AppSettings["{key-vault-secret-name}"];
            // Return the connection string value above, if blank, use the connection string value expected in the Web.config
            return string.IsNullOrWhiteSpace(connectionString) ? "MyContext" : connectionString;
        }
    }