【问题标题】:Private MEF import in UWPUWP 中的私有 MEF 导入
【发布时间】:2017-04-26 14:30:15
【问题描述】:

在 WPF 中,我可以使用 MEF (System.ComponentModel.Composition) 导入对私有属性的依赖项,如下所示:

[Import]
private IConfigService _service { get; set; }

我在 UWP 应用程序中通过 Microsoft.Composition NuGet 包使用 MEF,如果我的属性像这样公开,它可以正常工作:

 [Import]
 public IConfigService _service { get; set; }

但如果我将属性设为私有,它就不起作用。它不会抛出CompositionException,它只是将属性保留为null。有没有办法让它与私有属性一起使用?

更新

在对象上调用 CompositionHost.SatisfyImports 可以成功解决其依赖关系,但不能解决更远的依赖关系。在下面的示例中,在视图模型上调用 SatifyImports 将解析其高级服务,但不会解析低级服务。

[Export]
public class ViewModel
{
    [Import]
    private IHighLevelService _service { get; set; }
}

public interface IHighLevelService { }

[Export(typeof(IHighLevelService))]
public class HighLevelService : IHighLevelService
{
    [Import]
    private ILowLevelService _lowLevelService { get; set; }
}

public interface ILowLevelService { }

[Export(typeof(ILowLevelService))]
public class LowLevelService : ILowLevelService { }

【问题讨论】:

  • 您是否在创建的 CompositionHost 对象上调用了 SatisfyImports 方法以让 MEF 设置`_service` 属性?
  • 谢谢。这有点帮助,但这不是全部答案。请查看更新后的问题。

标签: c# uwp mef


【解决方案1】:

我找到了一个现在可以使用的解决方案,尽管它并不理想,因为它的反射开销很大。它是一种使用反射来查找所有具有 import 属性的属性,然后在每个属性上递归调用自身的方法。

public static class DependencyResolver
{
    public static CompositionHost Container { get; set; }

    public static void SatisfyImports(object arg)
    {
        Container.SatisfyImports(arg);

        var props = arg.GetType()
            .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Where(p => p.GetCustomAttributes().Contains(new ImportAttribute()));

        foreach (var prop in props)
        {
            object value = prop.GetValue(arg);
            SatisfyImports(value);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多