With MEF 1 it was possible to compose an existing object to the container with the ComposeExportedValue(...)-Method (container.ComposeExportedValue...
). How can this be done with Microsoft.Composition (MEF 2)? I can't find any Method for this purpose.
Compose exported value with MEF 2
1.6k views Asked by user31705 AtThere are 2 answers
I will have a shot at this one. Granted, I am only about a week in on learning MEF 2 myself, after having some limited exposure to MEF 1. So, please take that in consideration with the following answer as it could be completely wrong. Also, I have found documentation very poor and out of date so it has been an uphill battle in every respect thus far.
In my solution, I made use of the ExportDescriptorProvider
and extended it as an InstanceExportDescriptorProvider
as the following code demonstrates.
(Please note this should be considered proof-of-concept and not final code!)
public class InstanceExportDescriptorProvider : ExportDescriptorProvider
{
readonly object instance;
public InstanceExportDescriptorProvider( object instance )
{
this.instance = instance;
}
public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors( CompositionContract contract, DependencyAccessor descriptorAccessor )
{
if ( contract.ContractType.IsInstanceOfType( instance ) )
{
yield return new ExportDescriptorPromise( contract, contract.ContractType.FullName, true, NoDependencies, dependencies => ExportDescriptor.Create( ( context, operation ) => instance, NoMetadata ) );
}
}
}
Supporting test (using xUnit 2.0 paired with AutoFixture) to show how this would be used is as follows:
[Theory, AutoData]
public void VerifyInstanceExport( Assembly[] assemblies )
{
using ( var container = new ContainerConfiguration()
.WithProvider( new InstanceExportDescriptorProvider( assemblies ) )
.CreateContainer() )
{
var composed = container.GetExport<Assembly[]>();
Assert.Equal( assemblies, composed );
}
}
In my case I want to have access to the assemblies passed into the ContainerConfiguration
(not seen/tested in the above example) so that is why I am testing with Assemblies.
Hopefully this will be enough to get you on on your way. Or some way, in any case.
https://mef.codeplex.com/ states that
And as far as I know from my experience System.Composition doesn't support dynamic composition. If you need such capabilities you've got to use standard MEF (System.ComponentModel.Composition.*).