How to export a type in MEF as if the Export Attribute had been applied to that type?
Asked Answered
T

2

5

I would like to dynamically apply the MEF Export attribute to a type at run-time, exactly as if the type had had an Export attribute applied at compile time.

Is there a simple way to do this?

Barring that, is there a complex way to do this?

Tarbes answered 17/11, 2010 at 22:2 Comment(0)
M
7

If you can afford to use .NET 4.5 (which means dropping windows XP support), you can now use MEF's attribute-less registration aka Convention Model.

In .NET4 or earlier MEF preview releases this is not supported out of the box, but MEF can still be extended by creating your own implementations of ExportProvider or ComposablePartCatalog.

The MEF Contrib Fluent Definition Provider is such an implementation which allows you to register imports and exports by method calls.

The MEF Contrib Configurable Definition Provider is another which allows you to set up the imports and exports in an XML file.

Yet another option is to do the registration with Autofac and then use its MEF integration to make the autofac components available to MEF.

Martelli answered 18/11, 2010 at 9:35 Comment(3)
Thank you for this concise list of options.Tarbes
@WimCoenen I think for MEF 2 your own article might be better: mindinthewater.blogspot.nl/2011/03/…Robedechambre
@Zidad: Thanks for the remark, I've updated this (old) answer.Martelli
A
1

I'm not 100% sure but I don't think that's possible to do with MEF. One pattern to use to provide similar behavior though is the factory / provider pattern.

interface IData {} 

interface IDataProvider {
  IData Data { get; set; }
}

[Export(IDataProvider)]
class DataProvider : IDataProvider {
  public IData { get; set; }
}

You can use this pattern to dynamically update the implementation of IData to the value you would like to use.

Anzovin answered 17/11, 2010 at 22:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.