SonOfPirate
SonOfPirate

Reputation: 5494

Set non-injected parameters when importing objects using MEF

I have the following scenario in my Silverlight 4 application:

public class TheViewModel
{
    [Import()]
    public TheChild Child { get; set; }
}

[Export()]
public class TheChild
{
    [ImportingConstructor()]
    public TheChild(String myName, IAmTheService service) { ... }
}

[Export(typeof(IAmTheService))]
public class TheService : IAmTheService
{
    public void DoSomething(String theName);
}

As you can see, TheChild's constructor requires one imported parameter and one static value that is context-sensitive (has to be provided by the parent). The string value cannot come from AppSettings, configuration, etc. and can only be provided by the current instance of the parent class (TheViewModel in this case).

As a rule-of-thumb, I've always approached dependency-injection as follows:

  1. Required dependencies are satisfied through constructor injection
  2. Optional dependencies are satisfied through property injection

The "myName" parameter is required so I would prefer to set it through the constructor but given the way MEF works, I realize this may have to change.

Can you tell me how you've handled this scenario and your thoughts behind the solution?

Upvotes: 1

Views: 334

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564741

You can specify a specific import contract in conjunction with [ImportingConstructor]. For example:

[Export()]
public class TheChild
{
    [ImportingConstructor()]
    public TheChild([Import("MyName")] String myName, IAmTheService service) { ... }

Given that, an export of a string decorated with [Export("MyName")] will be required and used to fulfill the dependency. Any of the [Import] specifications should work in this case (ie: importing a subclass by type, importing by name, etc).

Upvotes: 1

Related Questions