简体   繁体   中英

How do I programatically modify the SqlCacheDependency section of web.config

I have this section in my web.config

<system.web>
    <caching>
      <sqlCacheDependency pollTime="60000" enabled="true">
        <databases>
          <add connectionStringName="CS" name="DB"/>
        </databases>
      </sqlCacheDependency>
    </caching>
</system.web>

I am trying to add a new entry in the <databases> element using this code

SqlCacheDependencySection section = ConfigurationManager.GetSection("system.web/caching/sqlCacheDependency") as SqlCacheDependencySection;
section.Databases.Add(new SqlCacheDependencyDatabase("DB2", "CS2", 60000)); 

But I receive an error that databases is read-only. The same goes for pollTime and enabled attributes.

So far I have managed to make them writable by setting the _bReadOnly private property to false using reflection

FieldInfo fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(section, false);

I'm not very comfortable using reflection to change the value of a private property in a sealed .net class. Also, I don't want to edit the web.config file using ConfigurationManager.OpenExeConfiguration because this would restart the worker process.

Is there another way to configure SqlCacheDependency in code behind?

这不是一个直接的答案,但是也许可以通过在部署时使用配置转换来解决您的问题。

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