C# - MEF - 从可移植类库导入

时间:2014-08-19 12:50:02

标签: c# mef portable-class-library

我似乎无法在常规Windows DLL中加载从PCL DLL导出的类。

我正在使用Nuget包:http://www.nuget.org/packages/Microsoft.Composition/(Microsoft Composition(MEF 2)1.0.27)

传递代码(在常规DLL中):

using System.ComponentModel.Composition;

namespace Normal
{
    [Export]
    public class TestExport
    {
    }
}

代码失败(在PCL DLL中):

using System.Composition;

namespace PCL
{
    [Export]
    public class TestExport
    {
    }
}

单元测试(常规单元测试项目):

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using PCL;

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace UnitTest
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            AggregateCatalog catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new AssemblyCatalog(typeof(PCL.TestExport).Assembly));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Normal.TestExport).Assembly));
            var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection);

            CompositionBatch batch = new CompositionBatch();
            batch.AddExportedValue(container);
            container.ComposeParts(batch);



            //Passes
            PCL.TestExport constructed = new PCL.TestExport();
            Normal.TestExport constructed2 = new Normal.TestExport();

            //Passes
            Normal.TestExport passes = container.GetExportedValue<Normal.TestExport>();


            //Fails
            PCL.TestExport e = container.GetExportedValue<PCL.TestExport>();
        }

    }

}

1 个答案:

答案 0 :(得分:2)

您的常规DLL和单元测试项目正在使用System.ComponentModel.Composition,即“MEF 1”。 MEF 1对System.Composition属性(MEF 2)一无所知。

如果您可以在所有项目中使用MEF 2,它应该可以正常工作。

相关问题