问题描述
我想创建一个使用依赖注入模式的 Xamarin 应用程序。我目前的问题是,除了作为依赖定位器反模式之外,我无法以任何其他方式与 xamarin 一起使用,而我想要一个实际的构造函数注入。我已经尝试了我能找到的所有东西,从 Prism 模板到 tinyIoC,但 viewmodels 和 Views 只需要一个无参数的构造函数。我错过了什么?
以下是一些有用但没有解决我的问题的来源
- Xamarin DependencyService with Parameterized Constructor
- https://docs.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/dependency-injection
- https://github.com/windows-toolkit/MVVM-Samples
我的应用程序是由 VS2019 生成的全新 xamarin 表单模板,我只添加了一些库,但这些库不应以任何方式干扰。 Xamarin 显然提供了一个内置的依赖定位器,但这不是我想要使用的。我还看到了一些实现了我想要的模板,但它们太大了,我无法弄清楚它们究竟是如何实现的。
理想情况下,我想使用 Microsoft MVVM Toolkit,但这不是一个严格的要求。我还希望实现尽可能简单,因为我刚刚开始使用 xamarin 开发。
我想要实现的一个例子:
public class Aboutviewmodel : Baseviewmodel
{
public Aboutviewmodel(ITest testService)
{
Title = "About";
OpenWebCommand = new Command(async () => await browser.OpenAsync("https://aka.ms/xamarin-quickstart"));
}
public ICommand OpenWebCommand { get; }
}
public interface ITest
{
void test();
}
class TestService : ITest
{
public void test()
{
Debug.WriteLine("Test successful");
}
}
解决方法
好的,我发现我的 AboutPage.xaml 中有这个
<ContentPage.BindingContext>
<vm:AboutViewModel />
</ContentPage.BindingContext>
似乎是一种在视图中初始化 viewModel 的简单方法,只是它只能接受无参数构造函数。这就是导致我出现问题的原因。将 ViewModel 初始化移动到后面的代码中解决了所有问题,尽管我仍然更愿意通过代码隐藏构造函数传递它。 这是现在的结果:
public AboutPage()
{
InitializeComponent();
BindingContext = Ioc.Default.GetRequiredService<AboutViewModel>();
}