I am relatively new to MEF so I don’t fully understand the capabilities. I’m trying to achieve something similar to Unity’s InjectionMember.
Let’s say I have a class that imports MEF parts. For the sake of simplicity, let’s take the following class as an example of the exported part.
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class Logger {
public string Category {
get;
set;
}
public void Write(string text) {
}
}
public class MyViewModel {
[Import]
public Logger Log {
get;
set;
}
}
Now what I’m trying to figure out is if it’s possible to specify a value for the Category property at the import. Something like:
public class MyViewModel {
[MyImportAttribute(Category="MyCategory")]
public Logger Log {
get;
set;
}
}
public class MyOtherViewModel {
[MyImportAttribute(Category="MyOtherCategory")]
public Logger Log {
get;
set;
}
}
For the time being, what I’m doing is implementing IPartImportsSatisfiedNotification and setting the Category in code. But obviously I would rather keep everything neatly in one place.
After more digging into MEF, it seems there’s no way to do this declaratively. While you can derive your own export attributes, there doesn’t appear to be any mechanism for deriving an import attribute in any meaningful way.
But instead of implementing IPartImportsSatisfiedNotification, what I can do (seems obvious now) is set the category in the setter. I have to give up the automatic property but that’s life.