在设置先决条件导入之前,无法调用GetExportedValue

我们在WPF应用程序中使用MEF

我们收到此错误

在先决条件导入’MyNamespace.MyMainClass..ctor(Parameter =“myParameter”,ContractName =“IContractInterface”)’已设置之前,无法调用GetExportedValue。

没有使用线程 ,我有时会读到这个错误发生在多个线程上,但是为了防止我创建了组合容器,将“thread safe”参数传递给了true

var container = new CompositionContainer(catalog, true); 

的守则是:

我的简化主类代码是:(想法是如果IMySubClass没有导入,我将使用默认的实现,这就是我在“OmImportsSatisfied”方法上创建它并满足其导入的原因。)

MyMainClass C#

 [Export(typeof(IMyInterface)] public class MyMainClass: IPartImportsSatisfiedNotification, IMyInterface { [Import] public IContainer Container { get; private set; } [Import(AllowDefault = true)] public IMySubClass MySubClass { get; set; } [ImportingConstructor] public MyMainClass([Import(AllowDefault = true)] IContractInterface myParameter= null) : this() { if (myParameter!= null) { //Do Something with myParameter } } public void OnImportsSatisfied() { if (MySubClass == null) { MySubClass = new MySubClass(); Container.SatisfyImportsOnce(MySubClass); } //Some other stuff } 

}

MySubClass C#

 public class MySubClass : IPartImportsSatisfiedNotification, IMySubClass { [ImportMany] public Lazy[] Exports { get; set; } public void OnImportsSatisfied() { foreach (var export in Exports) { var value = export.Value; //Here it throws the Exception //Do something. } } 

在OnImportSatisfied方法内的MySubClass中抛出错误

 var value = export.Value; 

但是,当我调试成功调用MyMainClass的ImportConstructor时,会注入并使用myParameter。 之后调用OnImportsSatisfied方法,我得到错误。


我的子类中的Exports列表来自具有属性“MyExportAttribute”的其他类中的属性。 我没有太多创建导出属性的经验,所以这里是代码,以防问题来自它。

导出属性

 public interface IMyAttributeInterfaceMetadata { string Property1 { get; } string Property2 { get; } } [MetadataAttribute] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public class MyExportAttribute : ExportAttribute, IMyAttributeInterfaceMetadata { string Property1 { get; } string Property2 { get; } public MyExportAttribute(string property1, string property2) : base(typeof(IMyAttributeInterface)) { Property1 = property1; Property2 = property2; } }