我想为一个接口创建一个基于委托的导出,该接口在每次撰写调用时都会调用,以便为每个使用者返回一个新实例。但显然我确实得到了同样的实例。这是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()));
}
}
}
预期产出:
实际输出