如何在运行时为Web API更改ConnectionStrings [英] How to Change ConnectionStrings at Runtime for a Web API

查看:58
本文介绍了如何在运行时为Web API更改ConnectionStrings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这是一个简单的问题:

I hope this is a simple question:

如何在运行时更改2个连接字符串 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);
}

详细信息

在我开始对为什么要这样做或为什么不这样做提出疑问之前,请参考以下帖子 Azure关键保管库连接字符串和N层设计.

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.

基本上,我正在尝试将Key Vault与N层应用程序一起使用.WebAPI通过 Web.config 定义连接字符串.为了避免对连接字符串进行硬编码,它们将存储在Key Vault中.但是,由于使用了 Unit of Work 模式,我不确定最佳途径,并且我目前正在尝试找出 injecting 更改连接字符串.

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.

推荐答案

我觉得我可能还没有理解这个问题(因为我对Azure Key Vault一无所知),但是您并没有真正获得连接字符串 Application_Start ...

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";
    }
}

现在,假设您具有上述功能,则可以使用它来初始化您的 DbContext :

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

MyDbContext myDbContext = new MyDbContext(GetConnectionString());

或者,如果要注入 DbContext ,则可以在DI代码中使用它(ninject示例):

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

这篇关于如何在运行时为Web API更改ConnectionStrings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆