我正在运行最新的 PRISM 4.2。不幸的是,文档中的事件聚合器教程是通过 Unity 而不是 MEF 驱动的。而且我无法让它在 MEF 下运行。
App.xaml.cs
public partial class App : Application
{
[Import]
public IEventAggregator eventAggregator;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Bootstrapper bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
}
Bootstrapper.cs
public class Bootstrapper : MefBootstrapper
{
protected override DependencyObject CreateShell()
{
return new MainWindow();
}
protected override void InitializeShell()
{
base.InitializeShell();
App.Current.MainWindow = (Window)Shell;
App.Current.MainWindow.Show();
}
protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
AggregateCatalog.Catalogs.Add(new AssemblyCatalog(this.GetType().Assembly));
}
protected override IModuleCatalog CreateModuleCatalog()
{
ModuleCatalog moduleCatalog = new ModuleCatalog();
return moduleCatalog;
}
}
MainWindow.xaml.cs
public partial class MainWindow : Window, IView
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
MainViewModel.cs:
[ModuleExport(typeof(MainViewModel))]
public class MainViewModel : BindableBase, IServiceCallback
{
[Import]
public IEventAggregator eventAggregator;
[ImportingConstructor]
public MainViewModel()
{
eventAggregator.GetEvent<AppExitEvent>().Publish("");
}
}
尽管 [import]
事件聚合器在 App.xaml.cs 和 MainViewModel 中始终为 null。这是为什么?
第二个问题是我是否必须将我的 Viewmodel 导出为一个模块(就像我上面所做的那样)才能在其中使用偶数聚合器?
更新:
证明 PRISM 的最新版本不再支持 ComposeExportedValue
。
'System.ComponentModel.Composition.Hosting.CompositionContainer' does not contain a definition for 'ComposeExportedValue' and no extension method ...
最佳答案
这个问题的解决方案是 SchubertJ 在 CodePlex 上对您的相同问题的回答:
作为更深入的分析,Properties 的Import 属性在构造函数完成之前不会被解析。这就是为什么如果要在构造函数实现上使用此依赖项,则需要通过构造函数注入(inject) EventAggregator 依赖项作为参数。
因此,如果您想使用 EventAggregator 对 ViewModel 构造函数的依赖,您应该使用 [ImportConstructor] 属性,并通过将其作为参数检索来向容器询问 EventAggregator 实例:
public class MainViewModel
{
private readonly IEventAggregator eventAggregator;
[ImportingConstructor]
public MainViewModel(IEventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
this.eventAggregator.GetEvent<MyEvent>().Publish("");
}
}
您可以在以下帖子中找到有关这两种导入替代方案的更多相关信息:
我希望这对你有帮助,问候。
关于c# - 如何在 MEF 中使用事件聚合器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21943396/