Как следует из названия, у меня внезапно возникли проблемы с запуском приложения .NET MAUI в Windows. Я получаю следующее исключение:
Exception thrown: 'System.TypeInitializationException' in forecAstIng.dll
An exception of type 'System.TypeInitializationException' occurred in forecAstIng.dll but was not handled in user code
The type initializer for '<Module>' threw an exception.
Из функции MauiProgram.CreateMauiApp() в автоматически создаваемом файле App.xaml.cs для конкретной платформы, который создается при запуске проекта MAUI:
using Microsoft.UI.Xaml;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace forecAstIng.WinUI
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public partial class App : MauiWinUIApplication
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
}
МауиПрограмма.cs:
using forecAstIng.View;
using Microsoft.Extensions.Logging;
using CommunityToolkit.Maui;
using forecAstIng.Services;
namespace forecAstIng
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseMauiCommunityToolkit()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
builder.Services.AddSingleton<DataService>();
builder.Services.AddSingleton<ForecastsViewModel>();
builder.Services.AddSingleton<MainPage>();
builder.Services.AddTransient<MorePageViewModel>();
builder.Services.AddTransient<MorePage>();
#if DEBUG
builder.Logging.AddDebug();
#endif
return builder.Build();
}
}
}
csproj:
<Project Sdk = "Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net8.0-android;net8.0-ios;net8.0-maccatalyst</TargetFrameworks>
<TargetFrameworks Condition = "$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net8.0-windows10.0.19041.0</TargetFrameworks>
<!-- Uncomment to also build the tizen app. You will need to install tizen by following this: https://github.com/Samsung/Tizen.NET -->
<!-- <TargetFrameworks>$(TargetFrameworks);net8.0-tizen</TargetFrameworks> -->
<!-- Note for MacCatalyst:
The default runtime is maccatalyst-x64, except in Release config, in which case the default is maccatalyst-x64;maccatalyst-arm64.
When specifying both architectures, use the plural <RuntimeIdentifiers> instead of the singular <RuntimeIdentifier>.
The Mac App Store will NOT accept apps with ONLY maccatalyst-arm64 indicated;
either BOTH runtimes must be indicated or ONLY macatalyst-x64. -->
<!-- For example: <RuntimeIdentifiers>maccatalyst-x64;maccatalyst-arm64</RuntimeIdentifiers> -->
<OutputType>Exe</OutputType>
<RootNamespace>forecAstIng</RootNamespace>
<UseMaui>true</UseMaui>
<SingleProject>true</SingleProject>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!-- Display name -->
<ApplicationTitle>forecAstIng</ApplicationTitle>
<!-- App Identifier -->
<ApplicationId>com.companyname.forecasting</ApplicationId>
<!-- Versions -->
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<ApplicationVersion>1</ApplicationVersion>
<SupportedOSPlatformVersion Condition = "$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">11.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition = "$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">13.1</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition = "$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition = "$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion>
<TargetPlatformMinVersion Condition = "$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion>
<SupportedOSPlatformVersion Condition = "$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>
</PropertyGroup>
<ItemGroup>
<!-- App Icon -->
<MauiIcon Include = "Resources\AppIcon\appicon.svg" Color = "#512BD4" BaseSize = "32,32" />
<!-- Splash Screen -->
<MauiSplashScreen Include = "Resources\Splash\splash.svg" Color = "#512BD4" BaseSize = "128,128" />
<!-- Images -->
<MauiImage Include = "Resources\Images\*" />
<!-- Custom Fonts -->
<MauiFont Include = "Resources\Fonts\*" />
<!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
<MauiAsset Include = "Resources\Raw\**" LogicalName = "%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
<None Remove = "resources\images\source.md" />
</ItemGroup>
<ItemGroup>
<PackageReference Include = "CommunityToolkit.Maui" Version = "9.0.3" />
<PackageReference Include = "CommunityToolkit.Mvvm" Version = "8.3.0" />
<PackageReference Include = "Microsoft.Maui.Controls" Version = "8.0.82" />
<PackageReference Include = "Microsoft.Maui.Controls.Compatibility" Version = "8.0.82" />
<PackageReference Include = "Microsoft.Extensions.Logging.Debug" Version = "8.0.0" />
<PackageReference Include = "Newtonsoft.Json" Version = "13.0.3" />
</ItemGroup>
<ItemGroup>
<MauiXaml Update = "View\SearchPrompt.xaml">
<Generator>MSBuild:Compile</Generator>
</MauiXaml>
</ItemGroup>
</Project>
Я использую dotnet8, так как считаю, что цели сборки также отображаются.
Я не уверен, актуально ли это, но незадолго до того, как я начал получать это исключение, я обновил пакеты nuget, которые использую для своего проекта, потому что у меня были другие проблемы со странными исключениями в окнах внутри моей программы. Я использую эти пакеты:
CommunityToolkit.Мауи
CommunityToolkit.Mvvm
Microsoft.Extensions.Logging.Debug
Microsoft.Maui.Controls
Microsoft.Maui.Controls.Совместимость
Microsoft.NET.ILLink.Tasks
Ньютонсофт.Json
🤔 А знаете ли вы, что...
C# поддерживает интероперабельность с кодом, написанным на C++, что позволяет использовать существующие библиотеки.
Поскольку ошибка возникает после обновления пакета Nuget, она возникает из-за конфликта версий пакета.
Исключите Newtonsoft.Json
, поскольку последний раз оно обновлялось 8.03.2023.
Исключите Microsoft.NET.ILLink.Tasks
, Microsoft.Extensions.Logging.Debug
, Microsoft.Maui.Controls
и Microsoft.Maui.Controls.Compatibility
, поскольку они автоматически загружаются при создании проекта. А Microsoft.NET.ILLink.Tasks не может изменить версию.
Итак, проблема в CommunityToolkit.Maui
и CommunityToolkit.Mvvm
, оба пакета недавно выпустили новые версии.
В конечном итоге проблема была решена путем понижения версии пакета CommunityToolkit.Mvvm
с 8.3.0 до 8.2.2. В настоящее время я не нашел на Maui Github проблемы о конфликтах версий пакета CommunityToolkit.Mvvm, вы можете опубликовать эту проблему на Maui Github.