MEF 导入属性

发布于 2024-09-26 08:41:20 字数 350 浏览 1 评论 0原文

使用 MEF,我知道您可以执行此操作来导入您的接口:

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

    private IUser m_userName;
}

我可以在方法内执行类似的操作吗?例如,下面的代码无法编译:

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

          userName.dosomething();
    }
}

Using MEF, I know you can do this to import your interface:

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

    private IUser m_userName;
}

Can I do something similar but within the method? For example, this below does not compile:

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

          userName.dosomething();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

二智少女猫性小仙女 2024-10-03 08:41:20

使用以下代码:

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

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

其中“container”是 CompositionContainer 实例:

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

Use this code:

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

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

Where 'container' is the CompositionContainer instance:

container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
container.ComposeParts(this);
鱼忆七猫命九 2024-10-03 08:41:20

正如您所看到的,您不能以这种方式使用导入。事实上,您永远无法在方法代码中使用属性,因此无法在方法中使用该属性。

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

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

As you've seen, you can't use Imports in that way. In fact you can't ever use an attribute inside method code, so there would be no way to use the attribute in a method.

You can however find exports of a given type by using the container, something like this:

IUser userName = (IUser)container.GetExports(typeof(IUser), null, null).FirstOrDefault();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文