Custom config section: Could not load file or assembly

前端 未结 7 2249
死守一世寂寞
死守一世寂寞 2020-12-15 05:50

I\'m having a very hard time trying to access a custom configuration section in my config file.

The config file is being read from a .dll that is loaded as a plug-in

7条回答
  •  心在旅途
    2020-12-15 06:09

    To expand on AJ's excellent answer, here is a custom class to assist with the overhead of registering and removing the global event.

    public sealed class AddinCustomConfigResolveHelper : IDisposable
    {
        public AddinCustomConfigResolveHelper(
            Assembly addinAssemblyContainingConfigSectionDefinition)
        {
            Contract.Assert(addinAssemblyContainingConfigSectionDefinition != null);
    
            this.AddinAssemblyContainingConfigSectionDefinition =
                addinAssemblyContainingConfigSectionDefinition;
    
            AppDomain.CurrentDomain.AssemblyResolve +=
                this.ConfigResolveEventHandler;
        }
    
        ~AddinCustomConfigResolveHelper()
        {
            this.Dispose(false);
        }
    
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
    
        private void Dispose(bool isDisposing)
        {
            AppDomain.CurrentDomain.AssemblyResolve -= this.ConfigResolveEventHandler;
        }
    
        private Assembly AddinAssemblyContainingConfigSectionDefinition { get; set; }
    
        private Assembly ConfigResolveEventHandler(object sender, ResolveEventArgs args)
        {
            // often the name provided is partial...this will match full or partial naming
            if (this.AddinAssemblyContainingConfigSectionDefinition.FullName.Contains(args.Name))
            {
                return this.AddinAssemblyContainingConfigSectionDefinition;
            }
    
            return null;
        }
    }
    

    I would suggest creating an instance in a using statement, like so:

    // you'll need to populate these two variables
    var configuration = GetConfiguration();
    var assembly = GetAssemblyContainingConfig();
    
    using(new AddinCustomConfigResolveHelper(assembly))
    {
        return (MyConfigSection)configuration.GetSection("myConfigSection");
    }
    

提交回复
热议问题