引用程序集的Visual C#app.config文件

Rus*_*ark 1 c# app-config reference visual-studio-2010

我们有一个Visual Studio 2010解决方案,其中包含几个符合Jeffery Palermo的Onion Architecture模式的C#项目(http://jeffreypalermo.com/blog/the-onion-architecture-part-1/).我们有一个UI项目,它是一个ASP.Net MVC项目,我们有一个名为Infrastructure的C#类库项目,由UI项目引用.在我们的基础结构项目中,我们添加了一个app.config文件,以包含特定于Infrastructure项目的设置.在运行时,app.config文件似乎不可用于Infrastructure项目,只有UI项目中包含的web.config文件.我们不希望将与Infrastructure项目相关的设置放入UI项目中的web.config文件中,UI不需要这些设置.我们如何在运行时使Infrastructure的app.config文件可用?我们想也许我们应该在构建应用程序时将一个Post Build Copy复制到UI目录中 - 这是正确的方法,

Dr.*_*ice 6

一般来说,你会被告知这是不可能做到的.但是,您当然可以使用System.Configuration.ConfigurationManager.OpenExeConfiguration方法加载配置文件.您可以将文件路径传递给程序集(尽管方法名称,它不必是可执行文件).

当然,这不会将程序集的配置设置合并到正在执行的应用程序的配置设置中,我认为它不应该.您的程序集必须知道它需要通过与System.Configuration.ConfigurationManager.GetSection函数或该类上的静态AppSettings属性不同的机制来检索其设置.

下面是一个"设置"类的一个非常简单的示例,该类为其所属的程序集加载.config文件.

public static class Settings
{
    public static System.Configuration.Configuration Configuration { get; private set; }

    static Settings()
    {
        // load a .config file for this assembly
        var assembly = typeof(Settings).Assembly;
        Configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(assembly.Location);

        if (Configuration == null)
            throw new System.Configuration.ConfigurationErrorsException(string.Format("Unable to load application configuration file for the assembly {0} at location {1}.", assembly.FullName, assembly.Location));
    }

    // This function is only provided to simplify access to appSettings in the config file, similar to the static System.Configuration.ConfigurationManager.AppSettings property
    public static string GetAppSettingValue(string key)
    {
        // attempt to retrieve an appSetting value from this assembly's config file
        var setting = Configuration.AppSettings.Settings[key];
        if (setting != null)
            return setting.Value;
        else
            return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法......

public class UsageExample
{
    void Usage()
    {
        string mySetting = Settings.GetAppSettingValue("MySetting");

        var section = Settings.Configuration.GetSection("MySection");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您仍然需要解决构建问题.将"应用程序配置文件"(App.config)项添加到类库程序集会导致Visual Studio将其作为.dll.config复制到该程序集的输出文件夹,但它不会自动复制到任何可执行应用程序的输出文件夹中那引用那个项目.因此,您需要添加一个生成后步骤,将文件复制到适当的位置,如您所述.

我考虑在类库上进行后构建步骤,将.config文件复制到解决方案级别的"Configurations"文件夹,然后为可执行项目创建一个后构建步骤,以复制"Configurations"文件夹中的所有内容到输出文件夹.我不知道,如果这样做的实际工作很好,但如果这样做,那么你就不会在你的后期生成步骤(这可能使维护困难)创建项目之间额外的依赖.

编辑:最后,您应该考虑这是否真的是您想要做的.这是不正常的做法,一般你可能会利用其他回答这个疑问,提到使用configSource属性得到更好的服务.

这种方法的缺点可能并不明显,那就是您无法将第三方组件的设置放入类库的配置文件中并期望它们被使用.例如,如果您的类库使用log4net,则无法将log4net的设置放在类库的配置文件中,因为log4net组件仍然希望从可执行文件的配置文件中加载设置.