RoLYroLLs
RoLYroLLs

Reputation: 3215

How to Change ConnectionStrings at Runtime for a Web API

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.

Upvotes: 8

Views: 1133

Answers (1)

Hooman Bahreini
Hooman Bahreini

Reputation: 15559

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();

Upvotes: 4

Related Questions