我正在尝试为MEF导出使用共享部分创建策略。然而,它并没有像我想的那样工作。我在应用程序中做了两次构图,并且每次都获得对象的新副本。我已经通过向对象实例添加实例计数器证明了这一点,并在调试中运行它。事实上,我第二次做的组成,我得到了FakeAutocompleteRepository的新副本instCount = 2,出口部分包含MEF创建策略
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IAutocompleteRepository))]
[ExportMetadata("IsTesting", "True")]
class FakeAutocompleteRepository : IAutocompleteRepository
{ ... }
有一些窍门能让同一个实例subsiquent请求?在情况下,它是什么成分时,我这样做是我正在做的是
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();
基本上我试图在测试过程中强制使用特殊的成分。如果你对单元测试这些组合有更好的想法,那么我就会全神贯注。
我完全在每次创建一个新的容器。有没有办法查询活动容器,或者应该在某处创建每个应用程序实例? – stimms 2009-05-05 13:47:02