【问题标题】:How do you export a type in MEF without the Export attribute? (eg programmatically)如何在没有 Export 属性的情况下在 MEF 中导出类型? (例如以编程方式)
【发布时间】:2026-02-05 11:50:02
【问题描述】:

我似乎找不到任何关于如何执行此操作的文章或链接,这似乎是一个明显的问题(例如,当您没有源代码或想要使用不是为 MEF 编写的现有类型时)

【问题讨论】:

    标签: .net mef


    【解决方案1】:

    如果您希望将现有对象实例添加到容器中,可以使用CompositionContainer.ComposeExportedValue 方法:

    container.ComposeExportedValue<MyClass>(myClassInstance);
    

    您真正需要的可能是新的基于约定的编程模型,它允许您根据命名约定而不是属性创建部件,但此功能仅在 .NET 4.5 中可用。

    使用示例(这将导出myAssembly 中实现IController 的每个类型为IController):

    var registration = new RegistrationBuilder();
    
    registration.ForTypesDerivedFrom<IController>()
                .Export<IController>();
    
    var catalog = new AssemblyCatalog(myAssembly, registration);
    var container = new CompositionContainer(catalog);
    

    如何使用 MEF 的新约定模型can be found here 的一个很好的例子。

    希望这会有所帮助。

    【讨论】:

    • 我想您的示例是基于预览版的?没有Implements 方法,instead 有很多ForType/ForTypes 方法。
    • @Stijn 你是对的,从那时起 API 发生了变化 - ForTypesDerivedFrom 已取代 Implements。我已经相应地编辑了我的答案。
    • 没有Add&lt;TInterface, TClass&gt;()Add&lt;TInterface&gt;(singleton)吗?
    【解决方案2】:

    如果您使用 InheritedExport 属性标记接口,则目录中的所有模块都将被导出,这些模块实现此接口,无论它们是否使用 Export 属性标记.

    界面:

    [InheritedExport]
    public interface IContract { ... }
    

    模块:

    // No [Export] attribute
    public class ModuleImplementation : IContract { ... }
    

    现在 MEF 将注入模块。

    【讨论】:

      最近更新 更多