【问题标题】:Using MEF to Import Types that Inherit from a given Interface使用 MEF 导入从给定接口继承的类型
【发布时间】:2015-11-07 14:12:04
【问题描述】:

[请注意,围绕这个主题有一些问题,但似乎没有一个与这个具体案例相匹配]

我有两个 ViewModel 可以导出自己的接口类型

[Export(typeof(ITestExplorer))]
public class TestExplorerViewModel : Tool, ITestExplorer, IDataErrorInfo, IDisposable
{
    // Implementation.
}

[Export(typeof(ITicker))]
public class TickerViewModel : Tool, ITicker, IDataErrorInfo
{
    // Implementation.
}

其中ITickerITestExplorer 都继承自同一个ICoreDataProvider 接口

public interface ITicker : ITool, ICoreDataProvider { }

public interface ITestExplorer : ITool, ICoreDataProvider { }

我知道这两个接口本质上是相同的,但是,它们是必需的,因为我使用 Caliburn micro 来启动某些视图类型,这些视图类型具有从上述每个接口继承的不同类。

我的问题是我希望[ImportMany]ICoreDataProviders,但我无法将上述类导出为ITickerICoreDataProvider(或ITestExplorerICoreDataProvider)[多个导出在一个单一属性]。我想做

[ImportMany]
private IEnumerable<IBetDataProvider> dataProviderCollection;

但我无法将导出类型切换为ICoreDataProvider,因为它们目前用于启动视图等。

  1. 我可以要求 MEF 导入“所有实现 ICoreDataProvider 的类型”,还是必须明确导出?
  2. 如果上面的答案是“是”,怎么办?如果“否”,还有其他使用 MEF 的方法吗?

我知道我可以通过类似的方式使用反射来伪造它

var instances = 
    from t in Assembly.GetExecutingAssembly().GetTypes()
    where t.GetInterfaces().Contains(typeof(ISomething))
         && t.GetConstructor(Type.EmptyTypes) != null
    select Activator.CreateInstance(t) as ISomething;

但我不喜欢这样,因为我需要对视图是否打开等进行各种检查。

感谢您的宝贵时间。

【问题讨论】:

    标签: c# wpf mvvm mef caliburn.micro


    【解决方案1】:

    我无法将上述类同时导出为 ITicker 和 ICoreDataProvider ... [单个属性中的多个导出]

    您可以将它们导出为两个接口,只需添加两次导出属性即可。

    [Export(typeof(ITestExplorer))]
    [Export(typeof(ICoreDataProvider))]
    public class TestExplorerViewModel : Tool, ITestExplorer, IDataErrorInfo, IDisposable
    {
        // Implementation.
    }
    
    [Export(typeof(ITicker))]
    [Export(typeof(ICoreDataProvider))]
    public class TickerViewModel : Tool, ITicker, IDataErrorInfo
    {
        // Implementation.
    }
    

    【讨论】:

    • 不可能,这么简单,我怎么错过了!?非常感谢...+1
    猜你喜欢
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2013-02-19
    相关资源
    最近更新 更多