How do you export a type in MEF without the Export attribute? (eg programmatically)
Asked Answered
R

2

11

I can't seem to find any articles or links to how to do this and it seems like an obvious problem (eg when you don't have the source code or want to use existing types not written for MEF in mind)

Rutherfurd answered 17/11, 2012 at 18:28 Comment(0)
E
16

If you're looking to add an existing object instance to your container, you can use the CompositionContainer.ComposeExportedValue method:

container.ComposeExportedValue<MyClass>(myClassInstance);

The thing you're really looking for though is probably the new convention-based programming model, which allows you to create parts based on naming conventions rather than attributes, but this feature is only available in .NET 4.5.

Usage example (this will export every type in myAssembly which implements IController as an IController):

var registration = new RegistrationBuilder();

registration.ForTypesDerivedFrom<IController>()
            .Export<IController>();

var catalog = new AssemblyCatalog(myAssembly, registration);
var container = new CompositionContainer(catalog);

A good example of how to use MEF's new convention model can be found here.

Hope this helps.

Embank answered 18/11, 2012 at 8:18 Comment(3)
I suppose you based your example on a preview version? There's no Implements method, instead there are a number of ForType/ForTypes methods.Cunha
@Stijn You're right, the API has changed since then - ForTypesDerivedFrom has replaced Implements. I've edited my answer accordingly.Embank
Isn't there a Add<TInterface, TClass>() or Add<TInterface>(singleton)?Fassold
T
10

If you mark an interface with the InheritedExport attribute, all modules within the catalog are exported, which implement this interface, whether they are marked with an Export attribute or not.

Interface:

[InheritedExport]
public interface IContract { ... }

Module:

// No [Export] attribute
public class ModuleImplementation : IContract { ... }

Now MEF will inject the module.

Trickster answered 22/11, 2012 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.