【问题标题】:How to set CreationPolicy singleton in .net-core System.Composition (Mef)如何在 .net-core System.Composition (Mef) 中设置 CreationPolicy 单例
【发布时间】:2018-10-12 23:39:33
【问题描述】:

我正在将 DNX 项目转换为 .net 核心。由于依赖关系的变化,我不能再使用System.ComponentModel.Composition,而是必须使用.net core 的移植版本System.Composition(我相信它被称为MEF 2)。

但是,我在 MEF2 中找不到用于为单例设置 CreationPolicy 的等效功能。 在 MEF1 中,代码为

[PartCreationPolicy(CreationPolicy.Shared)]

如何在 MEF2 中做到这一点?

【问题讨论】:

    标签: c# .net-core mef dnx mef2


    【解决方案1】:

    虽然没有很好的答案,但没有收到答案,所以自己回答。

    阅读多个帖子,似乎默认 CreationPolicy 是共享的,也就是单例。所以可能只是删除这一行就可以了。

    MEF2 引入了导出工厂,可以查看以获取有关策略设置的更多详细信息。

    【讨论】:

      【解决方案2】:

      解决方法是使用ConventionBuilder类。

      假设有一个名为AppShell 的类,它实现了接口IAppShell。为了以共享模式导出它,请按照以下步骤操作:

      var conventionBuilder = new ConventionBuilder();
      conventionBuilder.ForTypesDerivedFrom<IAppShell>()
          .Export<AppShell>()
          .Shared();
      

      然后:

      var config = new ContainerConfiguration()
          .WithAssemblies(new[]{ typeof(AppShell).Assembly}, conventionBuilder);
      

      【讨论】:

      • 有没有办法使用属性来做到这一点?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 2019-12-29
      • 2021-08-30
      相关资源
      最近更新 更多