我有一个使用依赖注入的 .Net Maui 应用程序。在我的 MauiProgram.cs 文件中,我将所有视图和视图模型添加到构建器服务中,如下所示:
builder.Services.AddSingleton<About>();
builder.Services.AddSingleton<Settings>();
builder.Services.AddSingleton<Places>();
builder.Services.AddSingleton<VM_MasterPage>();
builder.Services.AddSingleton<VM_About>();
builder.Services.AddSingleton<VM_AppSettings>();
builder.Services.AddSingleton<HelperClass>();
builder.Services.AddSingleton<VM_NearbyPlaces>();
我的视图模型的构造函数如下所示:
private VM_AppSettings localAppSettings;
/// <summary>
/// Constructor for the NearbyPlaces View Model
/// </summary>
public VM_NearbyPlaces(VM_AppSettings globalAppSettings )
{
this.GBSPlaceDetails = new ObservableCollection<GBSPlaceDetail>();
this.GBSRatings = new ObservableCollection<GBSRating>();
this.GBSAllPlacesMapInfo = new ObservableCollection<GBSPlaceMapInfo>();
localAppSettings = globalAppSettings;
//appSettings = GBSServiceProvider.GetService<VM_AppSettings>();
}
在 XUnit 测试的排列部分,我尝试创建视图模型的新实例,如下所示:
public class NearByPlacesTests
{
[Fact]
public async void NearbyPLacesInitalizeTest()
{
try
{
//Arrage - set up the classes etc.
var viewModelAppSettings = new VM_AppSettings(); **//I get the error here**
//We need to load all the preferences before we attempt to test
await viewModelAppSettings.Initialize(true);
var viewModelNearbyPlaces = new VM_NearbyPlaces(viewModelAppSettings);
//Act - call the functions that return the value(s) to check
await viewModelNearbyPlaces.InitializeData();
var placesCount = viewModelNearbyPlaces.GBSPlaceDetails.Count();
//Assert - check the value returned from the function with expected values.
//Check to ensure all the expected values are loaded.
Assert.True(placesCount > 0, "No places were returned.");
}
catch (Exception ex)
{
Assert.True(false, $"Error occured: {ex.Message}");
}
}
当我第一次运行测试时,我在代码中指示的行收到如下错误消息:
error could not load file or assembly 'Microsoft.Maui.Essentials
我根据我读到的另一篇堆栈溢出帖子,将以下行添加到“PropertyGroup”元素内的测试 cs 项目文件中。
<UseMauiEssentials>true</UseMauiEssentials>
添加 UseMauiEssential 行后运行测试时,我现在收到以下错误:
Could not load file or assembly 'Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
我又搜索了这个错误,但没有真正找到任何东西。以前有人遇到过这个错误吗?关于如何克服它有什么建议吗?
更新:我确实在 dotnet/maui 的 GitHub 问题中找到了此注释:
“然后是命令问题,您知道处理按钮点击的新方法。它们应该放置在您的虚拟机中以将 UI 绑定到。问题是,它们是在 Microsoft.Maui.Controls 中声明的 - - UI 引用....
该问题似乎表明此挑战已在 .Net 8 Preview 2 中得到解决 - 但我不想在我的应用程序中使用预览版本。
有谁知道应对此挑战的解决方法/解决方案吗?
在 .csproj 中使用此属性。对我来说效果很好。
<UseMaui>true</UseMaui>