我正在尝试在运行时加载插件并访问它们的配置文件。配置文件中的配置部分映射到从 ConfigurationElementCollection、ConfigurationElement 和 ConfigurationSection 派生的类。插件及其配置文件位于名为“Plugins”的子文件夹中。
问题是我似乎无法加载插件配置数据并将其正确反序列化到各自的类中。
这是插件 EmailPlugin.dll 的插件配置示例:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="EmailConfigurationSection" type="Foo.Plugins.EmailConfigurationSection, EmailPlugin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true"/>
</configSections>
<EmailConfigurationSection server="192.168.0.10">
<EmailSettings>
<add keyword="ERROR"
sender="error@error.com"
recipients="foo@bar.com, wiki@waki.com"
subject = "Error occurred"
body = "An error was detected"
/>
</EmailSettings>
</EmailConfigurationSection>
</configuration>
我使用以下代码加载它:
private static System.Configuration.Configuration config = null;
public static System.Configuration.Configuration CurrentConfiguration
{
get
{
if (config == null)
{
Assembly assembly = Assembly.GetAssembly(typeof(EmailPlugin));
string directory = Path.GetDirectoryName(assembly.CodeBase);
string filename = Path.GetFileName(assembly.CodeBase);
string assemblyPath = Path.Combine(directory, filename);
config = ConfigurationManager.OpenExeConfiguration(new Uri(assemblyPath).LocalPath);
}
return config;
}
}
这会导致错误:
An error occurred creating the configuration section handler for EmailConfigurationSection: Could not load file or assembly 'EmailPlugin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
我将此添加到配置文件的顶部:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="Plugins"/>
</assemblyBinding>
</runtime>
所以找到了 DLL,但是当我尝试检索它时它没有转换为正确的类:
EmailConfigurationSection defaults = CurrentConfiguration.Sections["EmailConfigurationSection"] as EmailConfigurationSection;
它总是返回 null。我知道它正在查看正确的位置和配置文件,因为我可以使用以下代码检索 XML:
var section = CurrentConfiguration.Sections["EmailConfigurationSection"];
string configXml = section.SectionInformation.GetRawXml();
但是,当我尝试使用以下代码对其进行反序列化时:
var serializer = new XmlSerializer(typeof(EmailConfigurationSection));
object result;
EmailConfigurationSection defaults;
using (TextReader reader = new StringReader(configXml))
{
defaults = (EmailConfigurationSection)serializer.Deserialize(reader);
}
...我得到一个例外:
There was an error reflecting type 'Foo.Plugins.EmailConfigurationSection'.
这是 InnerException 的内容:
You must implement a default accessor on System.Configuration.ConfigurationLockCollection because it inherits from ICollection.
我假设它指的是类 EmailConfigElementCollection,但是该消息没有意义,因为该类确实具有默认访问器:
public EmailConfigElement this[int index]
{
get
{
return (EmailConfigElement)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
我已在其他项目中成功使用此代码(即使使用单独的 DLL/配置),但这是我第一次尝试将它与 MEF 一起使用。有谁知道问题是什么,或者合适的解决方法?
我正在使用 .NET 4.5