问题
Is there a way to specify that a method gets called automatically after a part has been composed? The method could be called on the composed part or in the class doing the composition.
回答1:
Yes. If your class implements the IPartImportsSatisfiedNotification interface, then the MEF container will call OnImportsSatisfied
at the right time.
回答2:
Taking this approach will introduce a temporal coupling into your class - it will be dependent on some outsider calling methods in just the right order before it works properly.
Temporal Coupling is a major code smell - it makes reuse and understanding of the class much more difficult. (And keep in mind that one developer who will need to read and understand the code from scratch is yourself in six months.)
Instead, your class should take responsibility for it's own initialization - it shouldn't rely on an outside party.
One way to do this, if certain steps need to be deferred from the constructor, is to move those steps into a private method and then add a guard step to each appropriate public method ensuring the initialization is complete.
public class Example
{
public Example()
{
// Constructor
}
public void Open()
{
EnsureInitialized();
...
}
private void EnsureInitialized()
{
if (!mInitialized)
{
Initialize();
}
}
private void Initialize()
{
// Deferred code goes here
}
}
回答3:
Based on your comments the specific problem is there is code you want to execute only when the type is created via MEF composition. In other scenarios you'd like to avoid the code execution.
I'm not sure if there is a particular MEF event you could hook into. However you could use the following pattern to work around the problem
class MyPart {
public MyPart() : this(true) {
}
private MyPart(bool doMefInit) {
if (doMefInit) {
MefInitialize();
}
}
public static MyPart CreateLight() {
return new MyPart(false);
}
}
Although i would question the validity of this pattern. If your type has code which is only valid in a specific hosting scenario it screams that the code should likely be factored out into 2 independent objects.
来源:https://stackoverflow.com/questions/7615687/automatically-call-method-after-part-has-been-composed-in-mef