简体   繁体   中英

MEF Import Composition Issues

I've read all the questions I can find regarding the issues of composing imports without exporting the containing class but I can't find a solution to my problem. Does anybody know a way to achieve what I'm trying to do?

My module assemblies have forms and classes which they use internally. These forms need access to some of the exported contracts but imports are not loaded as they are not in the MEF 'composition tree'

Host assembly:

public class Host
{
    public Host()
    { /* Compose parts here... */ }

    [Export(typeof(Licence))]
    public Licence LoadedLicence { get; set; }  

    [Export(typeof(IModule))]
    public List<IModule> LoadedModules { get; set; }
}

Module assembly:

[Export(typeof(IModule))]
public class Module : IModule
{        
    public Module() { }

    public void DoSomething()
    {
        SubForm sub = new SubForm();
        sub.ShowDialog();
    }

    [Import(typeof(Licence))]
    public Licence LoadedLicence { get; set; } // This works here
}

public class SubForm : Form
{        
    public SubForm ()
    { }

    [Import(typeof(Licence))]
    public Licence LoadedLicence { get; set; } // This doesn't work in here
}

As far as I can see, my options are:

  1. Pass parameters to constructors (pain)
  2. Use a dummy export on the classes that need imports satisfying?

Any others?

I your specific case I would simply Export SubForm as its concrete type and Import in in Module. In that case all of its imports will be satisfied. Although if you expect to call DoSomething more than once then you will run into issues.

Another way people sometimes do this is to manually add the CompositionContainer to itself under the contract ICompositionService in your host and then have your module import ICompositionService and then everytime you create a SubForm you simply pass your object instance into ICompositionService.SatisifyImportsOnce to get its Imports satisfied.

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