How to Change ConnectionStrings at Runtime for a Web API

試著忘記壹切 提交于 2021-02-07 12:27:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/54835484/how-to-change-connectionstrings-at-runtime-for-a-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!