MEF忽略CreationPolicy

时间:2012-01-09 08:09:12

标签: c# mef

我想为一个接口创建一个基于委托的导出,该接口在每次撰写调用时都会调用,以便为每个使用者返回一个新实例。但显然我确实得到了同样的实例。这是MEF的限制(我使用的是.NET 4.0)吗?

以下是我尝试为每次撰写调用创建新实例的示例代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

namespace TestApp
{
    class Program
    {
        [Import(RequiredCreationPolicy = CreationPolicy.NonShared)]
        ITest Instance { get; set; }

        static void Main(string[] args)
        {
            CompositionContainer container = new CompositionContainer();
            CompositionBatch batch = new CompositionBatch();
            AddExportedValue<ITest>(batch, () =>
            {
                Console.WriteLine("Create new");
                return new Haha();
            }, CreationPolicy.NonShared);

            container.Compose(batch);

            Program p1 = new Program();
            container.SatisfyImportsOnce(p1);
            // Why do I see only one "Create new" print although CreationPolicy on import and export level is NonShared?
            container.SatisfyImportsOnce(p1);
        }

        interface ITest
        {}

        class Haha : ITest
        {}

        static ComposablePart AddExportedValue<iT>(CompositionBatch batch, Func<iT> factory, CreationPolicy policy)
        {
            string contractNameAndTypeIdentity = AttributedModelServices.GetContractName(typeof(iT));
            IDictionary<string, object> metadata = new Dictionary<string, object>();
            metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, contractNameAndTypeIdentity);
            metadata.Add(CompositionConstants.PartCreationPolicyMetadataName, policy); // <--- the policy seems to be ignored by MEF although incompatible policies are errored out with an exception.
            return batch.AddExport(new Export(contractNameAndTypeIdentity, metadata, () => factory()));
        }
    }
}

预期产出:

  • 新建
  • 新建

实际输出

  • 新建

1 个答案:

答案 0 :(得分:1)

您也可以将ExportFactory与.NET4.0一起使用。 Glenn Block刚刚发布了一个版本。我也在我的项目中使用它。