Container.Resolve<View>() 和 new View() 有什么区别?

What is difference between Container.Resolve<View>() and new View()?

现在我正在 Github 中用 "Prism-Samples-Wpf" 练习 Prism。 (https://github.com/PrismLibrary/Prism-Samples-Wpf/tree/master/06-ViewActivationDeactivation)

此代码是 MainWindow.xaml.cs

的一部分
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);
    }
}

有 return 个类似的类型。

(1) new ViewA();                 // ActivationDeactivation.Views.ViewA
(2) _container.Resolve<ViewB>(); // ActivationDeactivation.Views.ViewB

Container.Resolve() 和 new ViewA() 有什么区别?

What is difference between Container.Resolve<ViewA>() and 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 以了解一种非常简单的方法,让您的视图神奇地创建它们的视图模型(使用所有依赖项正确解析)。