MEF导入属性

时间:2010-10-05 17:08:25

标签: c# import mef

使用MEF,我知道你可以这样做来导入你的界面:

class MyClass
{
    [Import(typeof(IUser))]

    private IUser m_userName;
}

我可以在方法中做类似的事情吗?例如,下面的代码不能编译:

class MyClass
{
    public void DoWork()
    {
          [Import(typeof(IUser))]
          IUser userName;

          userName.dosomething();
    }
}

2 个答案:

答案 0 :(得分:1)

使用此代码:

IUser userName = container.GetExportedValue<IUser>();

if (userName != null)
{
    userName.dosoething();
}

其中'container'是CompositionContainer实例:

container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
container.ComposeParts(this);

答案 1 :(得分:0)

如您所见,您不能以这种方式使用Imports。事实上,您不能在方法代码中使用属性,因此无法在方法中使用该属性。

但是,您可以使用容器找到给定类型的导出,如下所示:

IUser userName = (IUser)container.GetExports(typeof(IUser), null, null).FirstOrDefault();