MEF(托管可扩展性框架)是否“躲避”打字?

时间:2009-07-17 00:29:57

标签: c# .net mef

我有2个集会:

装配1:

interface IWeapon {
    int Might { get; }
}

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

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

大会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");

我知道如何让它发挥作用。我可以向MEF(Managed Extensibility Framework)询问该对象,或者让它导出正确的IWeapon而不是按名称导出对象。

如果实现了所有接口点,MEF可以为我做“鸭子”打字并返回代理对象吗?

2 个答案:

答案 0 :(得分:5)

我认为在MEF的早期版本中存在(通过为类动态发送IL并返回它)并且它现在已被删除。这真的没有意义。毕竟,您的类应该设计以通过特定接口实现该加载项功能。如果您可以向其添加Export属性等内容,那么您应该完全能够在您的课程中实现该界面。

答案 1 :(得分:1)

如果你的两个IWeapon类都有相同的COM Guid,那么你可以在.NET 4中使用类型等价接近鸭子类型。对于使用MEF的插件的版本控制和升级支持非常好,即拥有v2合同也可以加载仅实现合同v1的插件。这是一篇关于这个主题的好文章。

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