简体   繁体   中英

How to export the type when interfaces are derived from base interface in MEF

Below is my scenario. I am trying to associate the types to the interfaces by using the Export functionality during the initial bootstrap. However, MEF complains on ImportCardinalityMismatchException.I am fairly new to MEF and I couldn't figure out what's wrong here? The easiest fix is to remove the inheritance. However, I would like to avoid it.

   public interface IColourService
    {
        Color GetColourByCountry(string countryName);
    }

    public interface IKnownColourService:IColourService
    {
        bool IsKnownCountry(string countryName);
    }

    public interface IUnKnownColourService:IColourService
    {
       bool IsUnKnownCountry(string countryName);
    }

    [Export(typeof(IColourService))]
    public class ColourService:IColourService
    {
       //implementation
    }

    [Export(typeof(IKnownColourService))]   
    public class KnownColourService:IKnownColourService
    {
       //implementation
    }

    [Export(typeof(IUnKnownColourService))]
    public class UnknownColourService:IUnKnownColourService
    {
       //implementation
    }

Can you not use IColourService as the Type in the Export attribute for all the classes?

[Export(typeof(IColourService))]

Then, you can access them with the following property declaration:

[ImportMany]
public IEnumerable<IColourService> ColourServices { get; set; }

And add a helper method to get specific types:

public IEnumerable<T> GetServices<T>()
{
    return ColourServices.OfType<T>().ToList();
}

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM