MEF: Mark interface for export

Can I mark the interface for export so that all derived classes are available for import?

[Export( typeof( IMyInterface ) )] public interface IMyInterface { ... } [Import( typeof( IMyInterface ) )] private readonly ICollection<IMyInterface> m_Concretes = new Collection<IPlugin>(); 

I do not know which classes implement IMyInterface in this example. Classes themselves do not know anything about MEF - and do not use the [Export] attribute.

Until I mark every class [Export] , it does not work for me.

+4
source share
3 answers

In the current preview, you can try placing the [PartExportsInherited] attribute on the interface (along with the Export attribute). I'm not sure if this will work for interfaces or not.

We plan to add support for export to interfaces.

+4
source

Yes, in the current preview on codeplex, you can mark the interface with both PartExportsInherited and Export, so that all developers are automatically exported. In the preview release of the preview, we are likely to optimize this to just put a single attribute, perhaps something like [InheritedExport].

Edit: With MEF 6 preview, this can now be done by placing the InheritedExport attribute in the interface.

+3
source

Update: Using MEF v4.

 [InheritedExport(typeof(IMyInterface))] public interface IMyInterface { } 

As expected, everything that inherits from IMyInterface will be exported as one.

Use [ImportMany] so that they are all entered:

 [ImportingConstructor] public void MyClass([ImportMany] IEnumerable<IMyInterface> myDerivedObjects) 
+2
source

Source: https://habr.com/ru/post/1286279/


All Articles