skb*_*skb 22 .net configuration app-config
我真的希望有一种方法可以使用ConfigurationManager.AppSettings ["mysettingkey"]获取当前获取其设置的应用程序,实际上这些设置来自集中式数据库而不是app.config文件.我可以创建一个自定义配置部分来处理这类事情,但我真的不希望团队中的其他开发人员必须更改他们的代码以使用我的新DbConfiguration自定义部分.我只是希望他们能够以他们一直以来的方式调用AppSettings,但是可以从中央数据库加载它.
有任何想法吗?
Pen*_*puu 25
如果你不介意破解框架,你可以合理地假设应用程序运行的.net框架版本(即它是一个Web应用程序或内部网应用程序),那么你可以尝试这样的事情:
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Internal;
using System.Reflection;
static class ConfigOverrideTest
{
sealed class ConfigProxy:IInternalConfigSystem
{
readonly IInternalConfigSystem baseconf;
public ConfigProxy(IInternalConfigSystem baseconf)
{
this.baseconf = baseconf;
}
object appsettings;
public object GetSection(string configKey)
{
if(configKey == "appSettings" && this.appsettings != null) return this.appsettings;
object o = baseconf.GetSection(configKey);
if(configKey == "appSettings" && o is NameValueCollection)
{
// create a new collection because the underlying collection is read-only
var cfg = new NameValueCollection((NameValueCollection)o);
// add or replace your settings
cfg["test"] = "Hello world";
o = this.appsettings = cfg;
}
return o;
}
public void RefreshConfig(string sectionName)
{
if(sectionName == "appSettings") appsettings = null;
baseconf.RefreshConfig(sectionName);
}
public bool SupportsUserConfig
{
get { return baseconf.SupportsUserConfig; }
}
}
static void Main()
{
// initialize the ConfigurationManager
object o = ConfigurationManager.AppSettings;
// hack your proxy IInternalConfigSystem into the ConfigurationManager
FieldInfo s_configSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.Static | BindingFlags.NonPublic);
s_configSystem.SetValue(null, new ConfigProxy((IInternalConfigSystem)s_configSystem.GetValue(null)));
// test it
Console.WriteLine(ConfigurationManager.AppSettings["test"] == "Hello world" ? "Success!" : "Failure!");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12052 次 |
| 最近记录: |