8

I hope this is a simple question:

How can you change 2 connection strings at runtime in the Global.asax under Application_Start()

Web.config

<connectionStrings>
  <add connectionString="DB1" value=""/>
  <add connectionString="DB2" value=""/>
</connectionStrings>

Global.asax

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Details

Before I start getting questions as to why I'm doing this or reasons I shouldn't, please refer to the following post Azure Key Vault Connection Strings and N-Layered Design.

Essentially, I'm trying to use Key Vault with an N-Layered application. The WebAPI defines the connection string via the Web.config. In order to avoid hard-coding connection strings, they will be stored in Key Vault. However, due to the Unit Of Work pattern used, I'm not sure the best route and I'm currently trying to figure out the potential solution of injecting or changing the connection string at runtime for the Web API project only.

RoLYroLLs
  • 3,113
  • 4
  • 38
  • 57

1 Answers1

4

I feel maybe I have not understood the question (as I don't know anything about Azure Key Vault), but you are not really getting your connection string in Application_Start...

Looking at this answer, I think you can implement a function which would return the desired connection string based on a variable:

string GetConnectionString()
{
    if (/* some dynamic variable is set */) {
        return  "DB1";
    }
    else {
        return "DB2";
    }
}

Now, assuming you have the above function, you can use it to initialize your DbContext:

MyDbContext myDbContext = new MyDbContext(GetConnectionString());

Or if you are injecting your DbContext, you can use it in your DI code (ninject example):

kernel.Bind<IMyDbContext>()
    .ToConstructor(ctorArg => new MyDbContext(GetConnectionString()))
    .InRequestScope();
Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137
  • Thanks for your answer. I have seen this potential solution, but I'm not sure how to implement it with the N-Layered solution I provided on the linked post (which is why I created this separate post specifically for Web.Config and ConnectionStrings. Maybe you can take look at the other post and help answer that: https://stackoverflow.com/q/54809790/286618 – RoLYroLLs Feb 25 '19 at 19:05
  • After a bit more research, I have found a few samples pointing to your ninject example to work with what I might be trying to do. I'm just not sure how to get it to work out just yet. – RoLYroLLs Feb 25 '19 at 19:29