用MEF 2构成出口值 [英] Compose exported value with MEF 2
问题描述
使用MEF 1,可以使用ComposeExportedValue(...)-方法( container.ComposeExportedValue ...
)将现有对象组成容器。如何使用Microsoft.Composition(MEF 2)完成此操作?我找不到用于此目的的任何方法。
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.
推荐答案
我将对此进行尝试。当然,在有限地接触MEF 1之后,我自己才学习MEF2。因此,请考虑以下回答,因为这可能是完全错误的。另外,我发现文档非常差且过时,因此到目前为止在各个方面都是艰巨的战斗。
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.
在我的解决方案中,我使用了< a href = https://github.com/dotnet/corefx/blob/master/src/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorProvider.cs rel = nofollow> ExportDescriptorProvider
并将其扩展为 InstanceExportDescriptorProvider
,如以下代码所示。
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 ) );
}
}
}
支持测试(使用 xUnit 2.0 与 AutoFixture ),以显示其用法,如下所示:
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 );
}
}
就我而言,我想访问程序集传递到 ContainerConfiguration
(在上面的示例中未看到/未测试),所以这就是为什么我要使用Assemblies进行测试。
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.
这篇关于用MEF 2构成出口值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!