动态加载程序集的应用程序配置 [英] App config for dynamically loaded assemblies

查看:28
本文介绍了动态加载程序集的应用程序配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将模块动态加载到我的应用程序中,但我想为每个模块指定单独的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆