MEF [导入] C#示例

问题描述

| 我在扩展一些现有的C#代码时遇到问题。 有一个一个类导出的管理器类的实例。 使用以下命令将其成功导入到其他几个类中:
[Import]
private Manager manager = null;
我已将相同的代码添加到新类中。它编译良好,但是在运行时引用始终为null。 我显然缺少了一些东西。 我真正想看到的是执行导入所需的最少代码(两个类)。 除了在一个类中创建和导出对象(最好不是字符串或简单值)之外,它不需要执行任何操作,并且在导入到另一个类时显示该对象为非空。 (我已经迷失在试图显示功能而不只是可用语法的其他示例的详细信息中。) 请注意,我需要查看一个使用[Import]而不是[Import(type)]的示例。 谢谢。     

解决方法

        我很确定这会起作用:
public class SampleClass
{
    [Import]
    private Manager manager; //Setting it to null is redundant.
}


[Export]
public class Manager
{
}
您还需要设置容器。有一些框架可以使所有内容的连接变得容易,但是如果没有的话。这并不困难: 在您的应用程序开始时,您需要填写目录:
//http://mef.codeplex.com/wikipage?title=Using%20Catalogs
var catalog = new AggregateCatalog();

//Add AssemblyCatalogs (Single) or DirectoryCatalogs (Multiple)
catalog.Catalogs.Add(new AssemblyCatalog(typeof(IManager).Assembly));
catalog.Catalogs.Add(new DirectoryCatalog(@\"myimports\\\"));

//Don\'t do this (including the same assembly twice)
//catalog.Catalogs.Add(new AssemblyCatalog(typeof(Manager).Assembly));

var container = new CompositionContainer(catalog);
container.composeParts(this);
但是,您确实应该利用接口进行导入/导出。
public class SampleClass
{
    [Import]
    private IManager Manager;
}

[InheritedExport]
public interface IManager { }

public class Manager : IManager { }
现在,就不必说出名称和类型了,但这是很好的,如果您计划具有需要区分的相似出口。
public class SomeClass
{
    //This is for the specific AdvancedManager
    [Import(\"AdvancedManager\",typeof(IManager))]
    private IManager AdvancedManager;

    //This is for the specific SimpleManager
    [Import(\"SimpleManager\",typeof(IManager))]
    private IManager SimpleManager;

    //If you don\'t mark it as ImportMany this will fail because now there
    //are 2 non-specific IManager exports.
    [ImportMany]
    private ICollection<IManager> AllManagers;
}

[InheritedExport]
public interface IManager { }

//This will export out as an IManager and a specifically named IManager
[Export(\"AdvancedManager\",typeof(IManager))]
public class AdvancedManager : IManager { }

//This will export out as an IManager and a specifically named IManager
[Export(\"SimpleManager\",typeof(IManager))]
public class SimpleManager : IManager { }
    ,        经理必须是财产。尝试
[Import]
private Manager manager { get; set; }