Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MEF (Managed Extensibility Framework) do "duck" typing?

Tags:

c#

.net

mef

I have 2 assemblies:

Assembly 1:

interface IWeapon {
    int Might { get; }
}

[Export("sword")]
public class Sword : IWeapon {

    public int Might {
        get { return 10; }
    }
}

Assembly 2:

interface IWeapon {
    int Might { get; }
}

var catalog = new AssemblyCatalog(typeof(Ninja.Sword).Assembly);
var container = new CompositionContainer(catalog);
// not allowed to use the IWeapon def in assembly 2 
var sword = container.GetExportedValue<IWeapon>("sword");

I know how to get this to work. I can either ask the MEF (Managed Extensibility Framework) for the object, or get it to export the correct IWeapon instead of just the object by name.

Can MEF do the "duck" typing for me and return a proxy object if all the interface points are implemented?

like image 707
Sam Saffron Avatar asked Jul 17 '09 00:07

Sam Saffron


2 Answers

I think it was there in early versions of MEF (by dynamically emitting IL for the class and returning it) and it's removed now. It really doesn't make sense. After all, your class should be designed to implement that add-in functionality through a specific interface. If you can add things like Export attribute to them, you should be perfectly able to implement the interface on your class too.

like image 197
mmx Avatar answered Oct 20 '22 22:10

mmx


If both of your IWeapon classes have the same COM Guid then you can get close to duck typing using type equivalence in .NET 4. It's really nice for versioning and upgrade support of plugins with MEF i.e. Having a v2 contract that can also load plugins that only implement v1 of the contract. Here is a good article on the subject.

http://blogs.msdn.com/b/delay/archive/2011/03/09/mef-addict-combining-net-4-s-type-embedding-and-mef-to-enable-a-smooth-upgrade-story-for-applications-and-their-extensions.aspx

like image 21
Aaron Stainback Avatar answered Oct 20 '22 20:10

Aaron Stainback