这是我之前发表的一篇文章的延续,其中涉及到解决WPF应用程序中的模块问题。这个问题与模块相互依存关系的影响以及构建这些模块的方法(即通过MEF或通过new
)具体涉及MEF解决关系的能力。无法解决MEF导入问题
我已经尝试了两种方法:
- 左侧的方法:应用实施IERROR
- 正确做法:在App具有实现IERROR
左胸成员
我的代码看起来像这样(只是MEF相关的东西):
// app.cs
[Export(typeof(IError))]
public partial class Window1 : Window, IError
{
[Import]
public CandyCo.Shared.LibraryInterfaces.IPlugin Plugin { get; set; }
[Import]
public CandyCo.Shared.LibraryInterfaces.ICandySettings Settings { get; set; }
private ICandySettings Settings;
public Window1()
{
// I create the preferences here with new, instead of using MEF. I wonder
// if that's my whole problem? If I use MEF, and want to have parameters
// going to the constructor, then do I have to [Export] a POCO (i.e. string)?
Settings = new CandySettings("Settings", @"c:\settings.xml");
var catalog = new DirectoryCatalog(".");
var container = new CompositionContainer(catalog);
try {
container.ComposeParts(this);
} catch(CompositionException ex) {
foreach(CompositionError e in ex.Errors) {
string description = e.Description;
string details = e.Exception.Message;
}
throw;
}
}
}
// plugin.cs
[Export(typeof(IPlugin))]
public class Plugin : IPlugin
{
[Import]
public CandyCo.Shared.LibraryInterfaces.ICandySettings CandySettings { get; set; }
[Import]
public CandyCo.Shared.LibraryInterfaces.IError ErrorInterface { get; set; }
[ImportingConstructor]
public Plugin(ICandySettings candy_settings, IError error_interface)
{
CandySettings = candy_settings;
ErrorInterface = error_interface;
}
}
// candysettings.cs
[Export(typeof(ICandySettings))]
public class CandySettings : ICandySettings
{
...
}
右侧接近
基本上一样的左侧的方式,所不同的是我创建的从IERROR继承在同一组件Window1中的类。然后我使用[Import]来尝试让MEF为我解决这个问题。
任何人都可以解释我在这里接触MEF的两种方式是否有缺陷?我一直处于黑暗中很长一段时间,而不是阅读关于MEF并尝试不同的建议,我已经将MEF添加到了我的解决方案中,并且正在进入代码中。它看起来像失败的部分是当它呼叫partManager.GetSavedImport()
。出于某种原因,importCache为空,我不明白。一直到目前为止,它一直在查看部件(Window1)并试图解析两个导入的接口 - IError和IPlugin。我会期望它输入代码,查看其他程序集在相同的可执行文件夹中,然后检查它的出口,以便它知道如何解决导入...
我发现我的代码中有错误,当我修正它时,MEF例外情况发生了变化,并且也更加有用。它明确指出它找不到CandySettings的默认构造函数!而挖掘更多,我发现一个good post from Glenn Block讨论这一点。所以我需要完成阅读并看看他的解决方法是否能解决问题。我仍然会喜欢更多的答案,因为不知道解决方法是否正确。
啊,所以*你*是我博客文章中的匿名评论者:-) – 2010-04-21 00:37:35