c# - 发现多个导出与 MEF ImportMany 的约束异常相匹配

标签 c# mef

我正在尝试在使用 MEF 加载一些插件的 WPF 应用程序上调试程序集导入问题,并寻找解决此特定异常的想法:

More than one export was found that matches the constraint:
ContractName MarkPad.Contracts.ISpellingService
RequiredTypeIdentity MarkPad.Contracts.ISpellingService

只有一个程序集直接引用关注的插件作为其 autofac 注册的一部分(最后的代码片段)。

[ImportingConstructor]
public SpellCheckPlugin(
    IPluginSettingsProvider settingsProvider,
    ISpellingService spellingService,
    ISpellCheckProviderFactory spellCheckProviderFactory)

只有 1 个 ISpellingService 实现

[Export(typeof(ISpellingService))]
public class SpellingService : ISpellingService

这是一个开源 Code52 project on github .

插件导入是:

[ImportMany]
IEnumerable<IPlugin> plugins;

到目前为止我尝试了什么:

  1. Thisthis blog帖子引用使用 [ImportMany(AllowRecomposition = true)] 但这似乎也没有帮助。
  2. 我发现的其他讨论提到将“复制本地”设置为 false,但因为它实际上用于注册代码,所以这不是一个选项,因为它最终不会出现在输出文件夹中。

有什么想法吗?

引用插件的注册码

builder.RegisterType<SpellingService>().As<ISpellingService>()
    .SingleInstance()
    .OnActivating(args =>
{
    var settingsService = args.Context.Resolve<ISettingsProvider>();
    var settings = settingsService.GetSettings<SpellCheckPlugin.SpellCheckPluginSettings>();
    args.Instance.SetLanguage(settings.Language);
})

最佳答案

解决方案

问题是当前程序集通过 GetExecutingAssembly 出现的错误在 PluginManager() 中用作 AggregateCatalog 中的目录条目之一正在提供给 CompositionContainer .

var catalog = new AggregateCatalog();

// This was causing the composition to detect additional imports
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

这个错误是由于将服务/插件提取到它们自己的程序集中而产生的,这些程序最初是核心 MarkPad 程序集的一部分。

Credit goes to @shiftkey and this patch.

额外改进

作为这个补丁的一部分,有一些额外的清理可能有助于支持这个答案。

由于 SpellCheckPlugin 采用接口(interface),导出只是简单地移动到接口(interface)本身而不是具体类型。

[ImportingConstructor]
public SpellCheckPlugin(
    IPluginSettingsProvider settingsProvider,
    ISpellingService spellingService,
    ISpellCheckProviderFactory spellCheckProviderFactory)

改为在接口(interface)上添加导出

[InheritedExport]
public interface ISpellCheckProviderFactory

// and

[InheritedExport]
public interface ISpellingService  

删除具体导出

[Export(typeof(ISpellingService))]
public class SpellingService : ISpellingService

// and

[Export(typeof(ISpellCheckProviderFactory))]
public class SpellCheckProviderFactory : ISpellCheckProviderFactory

关于c# - 发现多个导出与 MEF ImportMany 的约束异常相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11484109/

相关文章:

c# - System.Runtime.Numerics BigHexInteger 不工作

c# - 从 Shape 派生的 WPF 自定义形状类

c# - 我如何操作 NLog 的堆栈级别?

plugins - MEF 和版本控制

c# - 在 MEF 的泛型方法中转换类

c# - "in"具有原始值类型的修饰符?

c# - 如何使用表而不是 gridview?

c# - 我在哪里可以了解 MEF?

.net - 将 MEF 与 NHibernate 和 CaSTLe Windsor 一起使用

c# - 在设置先决条件导入之前无法调用 GetExportedValue