Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

GetExportedValue cannot be called before prerequisite import has been set?

$
0
0

We are using MEF in a WPF application.

And we are getting this error:

GetExportedValue cannot be called before prerequisite import 'MyNamespace.MyMainClass..ctor (Parameter="myParameter", ContractName="IContractInterface")' has been set.

I am not using threads, I read sometimes this error happens with multiple threads, just in case, I created the composition container passing the "thread safe" parameter in true

var container =newCompositionContainer(catalog,true);

The Code I have is:

My simplified Main Class code is: (The idea is that if there are not import for IMySubClass, I will use a default Implementation, that is why I create it on the "OmImportsSatisfied" method and satisfy its imports.)

MyMainClass C#

[Export(typeof(IMyInterface)]publicclassMyMainClass:IPartImportsSatisfiedNotification,IMyInterface{[Import]publicIContainerContainer{ get;privateset;}[Import(AllowDefault=true)]publicIMySubClassMySubClass{ get;set;}[ImportingConstructor]publicMyMainClass([Import(AllowDefault=true)]IContractInterface myParameter=null):this(){if(myParameter!=null){//Do Something with myParameter}}publicvoidOnImportsSatisfied(){if(MySubClass==null){MySubClass=newMySubClass();Container.SatisfyImportsOnce(MySubClass);}//Some other stuff}

}

MySubClass C#

publicclassMySubClass:IPartImportsSatisfiedNotification,IMySubClass{[ImportMany]publicLazy<IMyAttributeInterface,IMyAttributeInterfaceMetadata>[]Exports{ get;set;}publicvoidOnImportsSatisfied(){foreach(var export inExports){var value = export.Value;//Here it throws the Exception//Do something.}}

The error is thrown in MySubClass, inside the OnImportSatisfied method on the line:

var value = export.Value;

However when I debug the ImportConstructor of MyMainClass is called successfully, andmyParameter is injected and used. Afterwards the OnImportsSatisfied method is calledand I get the error.


The Exports list from my Subclass comes from properties in other classes that have the Attribute "MyExportAttribute". I don't have much experience creating Export Attributes, so here is the code in case the problem is coming from it.

Export Attribute

publicinterfaceIMyAttributeInterfaceMetadata{stringProperty1{ get;}stringProperty2{ get;}}[MetadataAttribute][AttributeUsage(AttributeTargets.Field|AttributeTargets.Property|AttributeTargets.Class,AllowMultiple=false,Inherited=false)]publicclassMyExportAttribute:ExportAttribute,IMyAttributeInterfaceMetadata{stringProperty1{ get;}stringProperty2{ get;}publicMyExportAttribute(string property1,string property2):base(typeof(IMyAttributeInterface)){Property1= property1;Property2= property2;}}

Dzyann.-


Viewing all articles
Browse latest Browse all 8156

Trending Articles