WPF 与 Unity 容器 - 如何注册 ViewModel 并将其解析为 View

2024-01-04

您好,我正在尝试在 WPF MVVM 应用程序中使用 Unity 容器。我没有使用过 Prism,因为它看起来很重。这是应用程序结构。我试图弄清楚如何将视图解析为视图模型以及视图模型(服务)的依赖关系。

应用:

Views

MainWindow.xaml
CustomerList.xaml
CustomerDetail.xaml
BookList.xaml
BookDetail.xaml

视图模型

MainViewModel

CustomerListViewModel

BoolListViewModel

BookDetailViewModel

CustomerDetailViewModel

Library

ICustomerService (AddCustomer, SaveCustomer, GetCustomers, GetCustomer)

CustomerService:ICustomerService

IBookService (GetBooks, GetBook)

BookService:IBookService

IBookReserveService(Reserve, Return)

BookReserveService:IBookReserveService
  1. MainViewModel需要引用ICustomerService和IBookService

  2. CustomerListViewModel 需要引用 ICustomerService

  3. BoolListViewModel 需要引用 IBookService

  4. BookDetailViewModel 需要引用 ICustomerService 和 IBookReserveService

  5. CustomerDetailViewModel 需要引用 ICustomerService 和 IBookReserveService

我在每个视图模型中都有服务的 getter setter 属性。

我遇到了如何在 WPF 中使用依赖注入的问题,特别是对于视图和 ViewModel。我尝试使用 Unity 在控制台应用程序中注册和解析,该应用程序工作正常。但我想要一些关于如何为 WPF 应用程序完成此操作的想法。我尝试注册

 container.RegisterType<ICustomerService, CustomerService>()
 container.RegisterType<IBookReserveService, BookReserveService>()
 container.RegisterType<IBookService, BookService>()

并使用解决它 容器.Resolve();

但我不确定如何判断哪个视图必须使用哪个视图模型,并在需要时而不是在应用程序启动时解析它们。另外,我不解析应用程序启动中的所有映射。应该在选择菜单(选择客户查看详细信息、选择书籍查看详细信息、保存客户、预订书籍等)时完成。

我读到的大部分内容都想使用 IView 和 IViewModel。但不确定我是否理解其中的优势。

任何帮助是极大的赞赏。


这是您可以执行此操作的一种方法。首先,向 Unity 注册您的视图模型和服务,如下所示:

// Unity is the container
_container.RegisterType<IMainViewModel, MainViewModel>();
_container.RegisterType<IBookService, BookService>();

其次,在视图的构造函数中将视图的 DataContext 设置为视图模型,如下所示:

public partial class MainView:UserControl
{
   private readonly IUnityContainer _container;

   public MainView(IUnityContainer container)
        {
            InitializeComponent();
            _container = container;   
            this.DataContext = _container.Resolve<IMainViewModel>();            
        }      
}

第三,您需要将服务注入到视图模型中:

public MainViewModel(ICustomerService custService, IBookService bookService ){}

还有其他方法可以使用 .config 文件等来执行此操作,但这应该足以让您开始使用,如果您需要更多,请告诉我。你问DI的优点是什么,我觉得有很多。仅举几个例子:促进组件之间的松耦合并提高可测试性。我觉得这是良好设计/实现的关键之一。

UPDATE:

对于 Unity >=3,如果遵循如下命名约定,则可以跳过容器注册:

// This will register all types with a ISample/Sample naming convention 
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF 与 Unity 容器 - 如何注册 ViewModel 并将其解析为 View 的相关文章

随机推荐