Change default app.config at runtime

后端 未结 8 2073
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 05:50

I have the following problem:
We have an application that loads modules (add ons). These modules might need entries in the app.config (e.g. WCF configuration). Because t

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:32

    Daniel's solution seems to work even for downstream assemblies I had used AppDomain.SetData before, but was unaware of how to reset the internal configuration flags

    Converted to C++/CLI for those interested

    /// 
    /// Remove cached values from ClientConfigPaths.
    /// Call this after changing path to App.Config.
    /// 
    void ResetConfigMechanism()
    {
        BindingFlags Flags = BindingFlags::NonPublic | BindingFlags::Static;
        Type ^cfgType = ConfigurationManager::typeid;
    
        Int32 ^zero = gcnew Int32(0);
        cfgType->GetField("s_initState", Flags)
            ->SetValue(nullptr, zero);
    
        cfgType->GetField("s_configSystem", Flags)
            ->SetValue(nullptr, nullptr);
    
        for each(System::Type ^t in cfgType->Assembly->GetTypes())
        {
            if (t->FullName == "System.Configuration.ClientConfigPaths")
            {
                t->GetField("s_current", Flags)->SetValue(nullptr, nullptr);
            }
        }
    
        return;
    }
    
    /// 
    /// Use your own App.Config file instead of the default.
    /// 
    /// 
    void ChangeAppConfig(String ^NewAppConfigFullPathName)
    {
        AppDomain::CurrentDomain->SetData(L"APP_CONFIG_FILE", NewAppConfigFullPathName);
        ResetConfigMechanism();
        return;
    }
    

提交回复
热议问题