简体   繁体   中英

MEF [Import] doesn't work when import object has [Import] to referenced assembly

I have project with structure like this (each box is separate assembly):

项目结构

I have plugin class in Plugin1 assembly:

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

    [Import] 
    private IDatabaseContextFactory f;
}

ILogger and it's implementation are in MyHost.Common assembly. IDatabaseContextFactory and it's implementation are in Database assembly.

MyHost.Host searches for exports marked as 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);
    }
}

When import in this line:

    [Import] 
    private IDatabaseContextFactory f;

is commented out it works, otherwise MEF raises exception: "No valid exports were found" for WcfService Import (not for IDatabaseContextFactory), or creates empty collection for ImportMany.

While debugging CompositionContainer looks the same for both cases.

EDIT:

CompositionContainer is built using this code:

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

        return new CompositionContainer(aggregateCatalog);

DatabaseContextFactory and Plugin1 are in dirAssembly.

I have finally found a solution!

There was a bug in database (import of non-existing service).

I wonder why the exception was on plugin, not database layer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM