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.

- 31
- 2
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.
-
Wow, this is quite ugly. I suspect you are correct in that WithProvider is the only way to do it. Fortunately it seems to be a catch-all that lets you fill in any holes in the api. There is github issue for composing exported values from an existing instance: https://github.com/dotnet/corefx/issues/11856 – David Beavon Aug 18 '17 at 03:54
https://mef.codeplex.com/ states that
System.Composition.*_ is a lightweight version of MEF, which has been optimized for static composition scenarios and provides faster compositions.
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.*).

- 243
- 2
- 11