动态加载的程序集的应用程序配置 [英] App config for dynamically loaded assemblies
问题描述
我正在尝试将模块动态加载到我的应用程序中,但是我想为每个模块分别指定单独的app.config文件.
I'm trying to load modules into my application dynamically, but I want to specify separate app.config files for each one.
说我对主应用程序有以下app.config设置:
Say I have following app.config setting for main app:
<appSettings>
<add key="House" value="Stark"/>
<add key="Motto" value="Winter is coming."/>
</appSettings>
另外一个我使用Assembly.LoadFrom
加载的库:
And another for library that I load using Assembly.LoadFrom
:
<appSettings>
<add key="House" value="Lannister"/>
<add key="Motto" value="Hear me roar!"/>
</appSettings>
两个库都有一个使用以下方法实现相同接口的类:
Both libraries have a class implementing the same interface, with the following method:
public string Name
{
get { return ConfigurationManager.AppSettings["House"]; }
}
请确保从主类和已加载的程序集输出Stark
都对Name
进行了足够的调用.
And sure enough calls to Name
from both main class and loaded assembly class output Stark
.
是否有一种方法可以使主应用程序使用其自己的app.config,而每个加载的程序集都使用其主程序?配置文件的名称在输出中是不同的,所以我认为应该是可能的.
Is there a way to make main app use its own app.config and each loaded assembly use theirs? Names of config files are different in the output, so that should be possible I think.
推荐答案
好,这是我最终得到的简单解决方案: 在实用程序库中创建关注函数:
Ok, here's the simple solution I ended up with: Create the follow function in the utility library:
public static Configuration LoadConfig()
{
Assembly currentAssembly = Assembly.GetCallingAssembly();
return ConfigurationManager.OpenExeConfiguration(currentAssembly.Location);
}
在动态加载的库中使用它,如下所示:
Using it in dynamically loaded libraries like this:
private static readonly Configuration Config = ConfigHelpers.LoadConfig();
无论该库如何加载,它都会使用正确的配置文件.
No matter how that library gets loaded it uses the correct config file.
对于将文件加载到ASP.NET应用程序中,这可能是更好的解决方案:
This might be the better solution for loading files into ASP.NET applications:
public static Configuration LoadConfig()
{
Assembly currentAssembly = Assembly.GetCallingAssembly();
string configPath = new Uri(currentAssembly.CodeBase).LocalPath;
return ConfigurationManager.OpenExeConfiguration(configPath);
}
要在构建后复制文件,您可能需要将以下行添加到asp应用程序的构建后事件中(从库中提取配置):
To copy file after build you might want to add the following line to post-build events for asp app (pulling the config from library):
copy "$(SolutionDir)<YourLibProjectName>\$(OutDir)$(Configuration)\<YourLibProjectName>.dll.config" "$(ProjectDir)$(OutDir)"
这篇关于动态加载的程序集的应用程序配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!