【发布时间】:2021-04-25 20:22:34
【问题描述】:
我正在创建一个简单的 WPF 应用程序,它有一个单一的视图和视图模型,它在视图模型中为执行计算的服务使用依赖注入。
App.xaml.cs:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<ICharacterCountService, CharacterCountService>();
container.RegisterType<IMathService, MathService>();
container.RegisterType<IMainWindowViewModel, MainWindowViewModel>();
ViewModelLocationProvider.Register<MainWindow, MainWindowViewModel>();
MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}
MainWindow.xaml:
<Window x:Class="MyFirstMVVM.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyFirstMVVM"
xmlns:prism="http://prismlibrary.com/"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="400"
prism:ViewModelLocator.AutoWireViewModel="True">
MainWindowViewModel中的构造函数:
public MainWindowViewModel(IMathService mathService, ICharacterCountService characterCountService)
{
_mathService = mathService;
_characterCountService = characterCountService;
AddCommand = new DelegateCommand(Add);
CountCommand = new DelegateCommand(Count);
}
如果您在视图模型中有一个无参数构造函数,您似乎只能使用ViewModelLocator,在这种情况下,我将无法注入CharacterCountService 和MathService。我是否必须使用另一种方法将视图 DataContext 设置为视图模型?
【问题讨论】:
-
提供者没有使用容器,因此不知道如何解决依赖关系。提供者需要一个工厂来知道如何解决依赖关系。
标签: c# wpf .net-core mvvm prism