我正在尝试将模块动态加载到我的应用程序中,但是我想为每个模块分别指定单独的app.config文件。

说我对主应用程序有以下app.config设置:

<appSettings>
  <add key="House" value="Stark"/>
  <add key="Motto" value="Winter is coming."/>
</appSettings>

还有另一个我使用Assembly.LoadFrom加载的库:
<appSettings>
  <add key="House" value="Lannister"/>
  <add key="Motto" value="Hear me roar!"/>
</appSettings>

这两个库都有一个使用以下方法实现相同接口(interface)的类:
public string Name
{
    get { return ConfigurationManager.AppSettings["House"]; }
}

并确保从主类和已加载的汇编类输出Name都对Stark进行了足够的调用。

有没有一种方法可以使主应用程序使用其自己的app.config和每个加载的程序集使用它们自己的?配置文件的名称在输出中是不同的,所以我认为应该是可能的。

最佳答案

好的,这是我最终得到的简单解决方案:
在实用程序库中创建关注函数:

public static Configuration LoadConfig()
{
    Assembly currentAssembly = Assembly.GetCallingAssembly();
    return ConfigurationManager.OpenExeConfiguration(currentAssembly.Location);
}

在动态加载的库中使用它,如下所示:
private static readonly Configuration Config = ConfigHelpers.LoadConfig();

无论该库如何加载,它都使用正确的配置文件。

编辑:
对于将文件加载到ASP.NET应用程序中,这可能是更好的解决方案:
public static Configuration LoadConfig()
{
    Assembly currentAssembly = Assembly.GetCallingAssembly();
    string configPath = new Uri(currentAssembly.CodeBase).LocalPath;
    return ConfigurationManager.OpenExeConfiguration(configPath);
}

要在构建后复制文件,您可能需要在asp应用程序的构建后事件中添加以下行(从库中提取配置):
copy "$(SolutionDir)<YourLibProjectName>\$(OutDir)$(Configuration)\<YourLibProjectName>.dll.config" "$(ProjectDir)$(OutDir)"

10-08 08:26
查看更多