我正在尝试将共享部件创建策略用于 MEF 导出。然而,它似乎不像我想的那样工作。我在我的应用程序中做了两次合成,每次都得到一个新的对象副本。我已经通过向对象实例化添加实例计数器来证明这一点
static int instCount = 0;
public FakeAutocompleteRepository()
{
instCount++;
...
}
并在调试中运行它。事实上,我第二次进行组合时,我得到了一个新的 FakeAutocompleteRepository 副本,其中 instCount = 2。导出部分包含
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IAutocompleteRepository))]
[ExportMetadata("IsTesting", "True")]
class FakeAutocompleteRepository : IAutocompleteRepository
{ ... }
是否有一些技巧可以为后续请求获取相同的实例?如果这是我在作曲期间正在做的事情,我就是这样做的
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog("."));
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);
if (null != ConfigurationSettings.AppSettings["IsTesting"] && bool.Parse(ConfigurationSettings.AppSettings["IsTesting"]))
repository = container.GetExports<IAutocompleteRepository>().Where(expDef => expDef.Metadata.Keys.Contains("IsTesting")).Single().GetExportedObject();
基本上我试图在测试期间强制使用特定的组合。如果您对这些作品的单元测试有更好的想法,那么我会全力以赴。