[英]Private MEF import in UWP
在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 { }
我发现了一个目前可以使用的解决方案,尽管它不理想,因为它的反射开销很大。 该方法使用反射来查找具有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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.