Create exported value using MEF 2

Using MEF 1, you could create an existing object for a container using ComposeExportedValue (...) - Method ( container.ComposeExportedValue...). How can this be done with Microsoft.Composition (MEF 2)? I can not find any method for this purpose.

+2
source share
2 answers

I will have a shot at this one. Of course, I worked for about a week, studying MEF 2, after the limited exposure to MEF 1. Therefore, please consider this with the following answer, as this may be completely wrong. Also, I found the documentation very poor and outdated, so until now it has been a tough battle in every way.

ExportDescriptorProvider InstanceExportDescriptorProvider, .

( , , !)

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 ) );
        }
    }
}

( xUnit 2.0 AutoFixture), , :

[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 );
    }
}

, ContainerConfiguration ( / ), .

, , . some, .

+2

https://mef.codeplex.com/ ,

System.Composition. * _ - MEF, .

System.Composition . , MEF (System.ComponentModel.Composition. *).

+1

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


All Articles