现在,我正在Github中使用“ Prism-Samples-Wpf”练习Prism。 (https://github.com/PrismLibrary/Prism-Samples-Wpf/tree/master/06-ViewActivationDeactivation)
此代码是MainWindow.xaml.cs的一部分
END
返回相同的类型。
public partial class MainWindow : Window
{
IContainerExtension _container;
IRegionManager _regionManager;
IRegion _region;
ViewA _viewA;
ViewB _viewB;
public MainWindow(IContainerExtension container, IRegionManager regionManager)
{
InitializeComponent();
_container = container;
_regionManager = regionManager;
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
_viewA = new ViewA();
_viewB = _container.Resolve<ViewB>();
_region = _regionManager.Regions["ContentRegion"];
_region.Add(_viewB);
_region.Add(_viewA);
}
}
Container.Resolve()和新的ViewA()有什么区别?
答案 0 :(得分:0)
Container.Resolve<ViewA>()
和new ViewA()
有什么区别?
完全没有(除了new
总是返回一个新实例,而ViewA
可能已注册为单例)。
但是想象一下new SomeService( aDependency, new AnotherDependency(), () => new SomeProduct( new ThirdDependency(), aDependency )
而不是Container.Resolve<SomeService>()
...
Unity或任何DI容器(即 just )使创建实例时的工作更加轻松。当然,您可以手动完成所有操作,而不必这样做。不过要小心-您不应该 注入容器。如果必须动态创建实例,则可以注入工厂。
MainWindow
的示例如下:
public partial class MainWindow : Window
{
private readonly Func<ViewA> _viewAFactory;
private readonly Func<ViewB> _viewABFactory;
IRegionManager _regionManager;
IRegion _region;
ViewA _viewA;
ViewB _viewB;
public MainWindow(Func<ViewA> viewAFactory, Func<ViewB> viewBFactory, IRegionManager regionManager)
{
InitializeComponent();
_viewAFactory = viewAFactory;
_viewBFactory = viewBFactory;
_regionManager = regionManager;
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
_viewA = _viewAFactory();
_viewB = _viewBFactory();
_region = _regionManager.Regions["ContentRegion"];
_region.Add(_viewB);
_region.Add(_viewA);
}
}
所有这些实际上都应该在MainWindowViewModel
中发生。看看ViewModelLocator
,这是一种非常简单的方法来使您的视图神奇地创建其视图模型(正确解决了所有依赖关系)。