简体   繁体   中英

Taking variables out of the web.config to assign dynamically

I'm using sql dependent caching in my ASP.NET application, and to achieve this I have the following entry in the web.config:

<connectionStrings>
  <add name="DatabaseName" connectionString="Data Source=.\Dev;Initial Catalog=DatabaseName;Integrated Security=True" />
</connectionStrings>

<system.web>
  <caching>
    <sqlCacheDependency enabled="true">
      <databases>
        <add name="DatabaseName" connectionStringName="DatabaseName"/>
      </databases>
    </sqlCacheDependency>
  </caching>
</system.web>

In the application, a SqlCacheDependency is created using the name of the database that is specified in the web.config, like this:

var tableDependency = new SqlCacheDependency("DatabaseName", "TableName");

What I want to achieve is removing the need for the connection string in the web.config, as this application's connection string is likely to change when placed onto different servers.

There is already a connection string class in the application that returns the correct string for what server it is currently on, so without using that, I will have to manually change the connection string in the web.config on each server.

Thanks in advance,

Greg.

As far as I can tell, the "code behind" of sqlCacheDependency is taking the connection string directly from the config file, so it must be there.

Leave the connectionstrings section empty in the web.config then use the code from this question to programmatically add the proper connection string.

You need to put it in a place that is called before any other code, maybe even Handler or Module, otherwise the sqlCacheDependency might not "catch" the proper value. Maybe the Application_Start of global.asax will be enough.

我相信您可以使用SqlCacheDependencyAdmin类以编程方式设置缓存依赖项,因此您不必依赖SqlDependency从web.config文件中读取设置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM