Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are Property Imports Satisfied?

Tags:

c#

mef

When are property imports satisfied? I thought they would be satisfied before the constructor, as properties are initialized before the constructor runs, but the following example shows ImportedClass to be null in the constructor.

I know I can resolve this by using an ImportingConstuctor; this is for sake of understanding when the property imports are satisfied.

public MyClass
{
  [Import]
  public ImportedClass ImportedClass {get;set;}

  public MyClass()
  {
      //Imported Class is null at this point, so nothing can be done with it here.
  }
}
like image 940
Greg Gum Avatar asked Mar 22 '23 19:03

Greg Gum


1 Answers

An object cannot be manipulated before its constructor is being called. MEF provides a solution for your problem though, with an interface called IPartImportsSatisfiedNotification

public MyClass : IPartImportsSatisfiedNotification
{
  [Import]
  public ImportedClass ImportedClass {get;set;}

  public MyClass()
  {
      //Imported Class is null at this point, so nothing can be done with it here.
  }

  public void OnImportsSatisfied() 
  {
     //ImportedClass is set at this point.
  }
}

About the actions MEF takes to set your imports; it first calls the constructor, then sets any properties, then calls the notification method.

like image 66
Bas Avatar answered Apr 20 '23 07:04

Bas