App config for dynamically loaded assemblies

前端 未结 3 1085
执念已碎
执念已碎 2021-02-04 09:42

I\'m trying to load modules into my application dynamically, but I want to specify separate app.config files for each one.

Say I have following app.config setting for ma

3条回答
  •  野的像风
    2021-02-04 10:08

    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.

    Edit: 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);
    }
    

    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)\$(OutDir)$(Configuration)\.dll.config" "$(ProjectDir)$(OutDir)"
    

提交回复
热议问题