1

我使用 DictionaryAdapter 从我的 asp.net 网站的 appSettings 部分检索设置。IoC 配置在启动时完成一次,并且使用单个 Configuration.AppSettings 对象注册各种具有 getter 的不同接口:

 var dictionaryAdapterFactory = new DictionaryAdapterFactory();
        container.Register(
            Types
                .FromAssemblyNamed(assemblyName)
                .Where(t => t.Name.EndsWith("AppSettings"))
                .Configure(
                    component => component.UsingFactoryMethod(
                        (kernel, model, creationContext) =>
                        dictionaryAdapterFactory.GetAdapter(creationContext.RequestedType, ConfigurationManager.AppSettings))));

Web.config 文件中托管的 appSettings 部分工作正常,但当我想在运行时更新某些设置时它有其缺点。因为它是 web.config 文件,所以整个应用程序被重新启动。我希望能够在运行时修改配置而不会重新启动网站作为副作用。因此,我搬到了单独的文件中:

<appSettings configSource="AppSettings.config">

现在,通过 ConfigurationManager.AppSettings["key"] 检索它们时会反映更改,但在通过 DictionaryAdapter 的动态接口访问时不会反映更改。

有没有办法告诉 DA 观察源代码的变化而不是缓存值?

4

2 回答 2

1

Although I didn't find the exact answer, I found a workaround. Instead of 'binding' DA directly to ConfigurationManager, i bind to a simple proxy that wraps CM:

public class AppSettingsProxy : NameValueCollection
{
    public override string Get(string name)
    {
        return ConfigurationManager.AppSettings[name];
    }

    public override string GetKey(int index)
    {
        return ConfigurationManager.AppSettings[index];
    }
}

Then jus tchange binding to my proxy instance:

  container.Register(
            Types
                .FromAssemblyNamed(assemblyName)
                .Where(t => t.Name.EndsWith("AppSettings"))
                .Configure(
                    component => component.UsingFactoryMethod(
                        (kernel, model, creationContext) =>
                        dictionaryAdapterFactory.GetAdapter(creationContext.RequestedType, appSettingsProxy))));

The above works for me. While I can modify my website's settings at runtime without an restart, value changes now are reflected via dynamically generated proxes over my settings interfaces.

于 2013-06-21T13:42:38.070 回答
0

DictionaryAdapter 默认情况下本身并不缓存这些值。这是一个通过测试来证明这一点。

    public interface IFoo
    {
        string Foo { get; set; } 
    }

    [Test]
    public void Adapter_does_not_cache_values_once_read()
    {
        var dict = new NameValueCollection { { "Foo", "Bar" } };

        var adapter = (IFoo)factory.GetAdapter(typeof(IFoo), dict);

        var value = adapter.Foo;

        dict["Foo"] = "Baz";
        var value2 = adapter.Foo;

        Assert.AreNotEqual(value, value2);
        Assert.AreEqual("Baz", value2);
    }

您确定自己没有在代码中缓存值吗?你能在测试中重现这种行为吗?

于 2013-06-21T04:41:26.573 回答