c# - 尝试学习 MEF 时遇到困难

标签 c# .net mef

我一直在尝试自学 MEF,从本教程开始:

http://blogs.msdn.com/b/brada/archive/2008/09/29/simple-introduction-to-composite-applications-with-the-managed-extensions-framework.aspx

与 MEF 在本教程中的工作方式相比,MEF 现在的工作方式存在一些差异。一个区别是 CompositionBatch 对象;但是,我想我了解所做的更改。

不过,我似乎无法理解的一个区别是,尽管教程说我应该能够通过更改属性的返回类型来处理 0/1/多个导入,但我无法在实践。下面我将粘贴给我错误的代码;谁能告诉我为什么这不起作用以及我应该怎么做?

我最终将使用 MEF 创建一个基于插件的应用程序,该应用程序将在运行时通过将实现特定接口(interface)的不同 .dll 文件放入目录中来添加不同的功能。我想我会为此使用 DirectoryCatalog,但我想我需要先了解这个障碍。

namespace MessinWithMef
{
    class Program
    {
        [Import]
        public IEnumerable<string> Message { get; set; }

        public void Run()
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var batch = new CompositionBatch();

            batch.AddPart(this);

            var container = new CompositionContainer(catalog);
            container.Compose(batch);

            foreach (var s in Message)
            {
                Console.WriteLine(s);
            }

            Console.ReadKey();
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.Run();
        }
    }

    public class SimpleHello
    {
        [Export]
        public string Message
        {
            get
            {
                return "Hello world!";
            }
        }
    }

    public class ExtraHello
    {
        [Export]
        public string OtherMessage
        {
            get
            {
                return "Hi there!";
            }
        }
    }
}

这是错误的文本:

The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.

1) No valid exports were found that match the constraint '((exportDefinition.ContractName == "System.Collections.Generic.IEnumerable(System.String)") AndAlso (exportDefinition.Metadata.ContainsKey("ExportTypeIdentity") AndAlso "System.Collections.Generic.IEnumerable(System.String)".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity"))))', invalid exports may have been rejected.

Resulting in: Cannot set import 'MessinWithMef.Program.Message (ContractName="System.Collections.Generic.IEnumerable(System.String)")' on part 'MessinWithMef.Program'.
Element: MessinWithMef.Program.Message (ContractName="System.Collections.Generic.IEnumerable(System.String)") -->  MessinWithMef.Program

最佳答案

如果要解析多个匹配的导出,则必须使用 [ImportMany]

请注意,在插件类型的场景中,您可能想要使用 ExportMetadata,然后决定您实际想要实例化哪些插件。然后你会做类似的事情:

[ImportMany]
IEnumerable<Lazy<IPlugin, IPluginMetadata>> _possiblePlugins;

现在您的代码可以枚举可能的插件,检查元数据,然后决定是否实例化每个惰性导入。

关于c# - 尝试学习 MEF 时遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6230932/

相关文章:

c# - BlockingCollection + UI 线程

c# - 我是否正确认为这个 async-await 示例没有做任何有用的事情?

c# - 重复代码位的设计模式/C#技巧

c# - 模块类型加载异常 : Failed to load type for module

c# - 服务定位器 : Get all exports

c# - 在 C# 应用程序中使用 Plink session 时逃避 SSH 主机验证

c# - 意外错误 : LINQ to Entities does not recognize the method 'System.String DecryptValue(Byte[], System.String)' method

c# - 如何为当前用户(Sitecore)添加新的访客标签?

c# - 静态类必须派生自对象 (C#)

c# - 如何从通过 MEF 注入(inject)的代码创建向导界面?