katit
katit

Reputation: 17905

How do I tell MEF which type I need for this interface?

I have following:

public interface IEmailService
    {
        bool SendEmail(MailMessage message);
    }

[Export(typeof(IEmailService))]
    public class SmtpEmailService : IEmailService
    {
}


[Export(typeof(IEmailService))]
    public class AmazonEmailService : IEmailService
    {
}

How do I import specific one based on some criteria?

For example, when I use service I have something like this:

public class MobileService
    {
        [Import] 
        public IEmailService EmailService { get; set; }

Is there any way to configure MEF in config file or any other place so it KNOWS automatically which version of EmailService to import?

Upvotes: 2

Views: 299

Answers (1)

S2S2
S2S2

Reputation: 8502

You can specify the name of the contract in your Export attribute while exporting and then use one of the names you exported in your Import attribute as below:

[Export("SmtpEmailService", typeof(IEmailService))]
public class SmtpEmailService : IEmailService {
}

[Export("AmazonEmailService", typeof(IEmailService))]
public class AmazonEmailService : IEmailService {
}

[Import("AmazonEmailService")]
public IEmailService EmailService { get; set; } //Import a specific type

In case you also want to use ImportMany, see the section Exports and Metadata on http://mef.codeplex.com

There is also a similar SO question which should help you.

Upvotes: 3

Related Questions