当导入对象具有[导入]到引用的程序集时,MEF [导入]不起作用

时间:2015-09-08 12:10:30

标签: c# wcf

我有这样的结构项目(每个框都是单独的程序集):

Project structure

我在Plugin1程序集中有插件类:

[Export("WcfService")]
public class Plugin1 : BaseService, IPlugin1
{
    [Import]
    private ILogger _logger;

    [Import] 
    private IDatabaseContextFactory f;
}

ILogger及其实现在MyHost.Common程序集中。 IDatabaseContextFactory及其实现在数据库程序集中。

MyHost.Host搜索标记为WcfService的导出。

[Export(typeof(IHost))]
internal class Host : IHost
{
    private class MefContainerHelper
    {
        [ImportMany("WcfService")]
        public IList<object> Services = new List<object>();
    }

    public void LoadServicesFromCompositionContainer(CompositionContainer compositionContainer)
    {
        var helper = new MefContainerHelper();
        compositionContainer.SatisfyImportsOnce(helper);
    }
}

在此行中导入时:

    [Import] 
    private IDatabaseContextFactory f;

被注释掉它有效,否则MEF引发异常:&#34;没有找到有效的出口&#34; for WcfService Import(不适用于IDatabaseContextFactory),或为ImportMany创建空集合。

虽然调试CompositionContainer在两种情况下都看起来相同。

编辑:

使用以下代码构建CompositionContainer:

        var commonAssembly = new AssemblyCatalog(typeof(ILogger).Assembly);
        var dirAssembly = new DirectoryCatalog("./Plugins/");
        var aggregateCatalog = new AggregateCatalog(commonAssembly, dirAssembly);

        return new CompositionContainer(aggregateCatalog);

DatabaseContextFactory和Plugin1在dirAssembly中。

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案!

数据库中存在错误(导入非现有服务)。

我想知道为什么异常是在插件上,而不是数据库层。