dotnet / maui

.NET MAUI is the .NET Multi-platform App UI, a framework for building native device applications spanning mobile, tablet, and desktop.
https://dot.net/maui
MIT License
22.18k stars 1.74k forks source link

XamlParseException when using dependency injection #14911

Open Sebosek opened 1 year ago

Sebosek commented 1 year ago

Description

Using the dependency injection mechanism in App.xaml.cs causes the Microsoft.Maui.Controls.Xaml.XamlParseException (full text is the following: Microsoft.Maui.Controls.Xaml.XamlParseException: 'Position 11:13. StaticResource not found for key Yellow300Accent'). The constructor parameter is a type of MainPage and the Main Pase uses Yellow300Accent from static resources to set background color. The MainPage class is registered as transient (in fact, setting a different class lifetime strategy doesn't have any impact). A similar error has been already reported about a year ago https://github.com/dotnet/maui/issues/5868.

Steps to Reproduce

  1. Clone the repository https://github.com/Sebosek/BrokenConstructor (or create an empty MAUI app, bind the background color of VerticalStackLayout to StaticResource Yellow300Accent in MainPage, then register the MainPage as Transient to the DI container, and use MainPage as parameter type for App.xaml.cs + set this parameter as MainPage)
  2. Run the application in an Android emulator (Android 12, API 31) or a Windows Machine

Current behaviour: The application throws the XamlParseException.

Expected behaviour: The application runs as expected with the selected background color.

Link to public reproduction project repository

https://github.com/Sebosek/BrokenConstructor

Version with bug

7.0 (current)

Last version that worked well

Unknown/Other

Affected platforms

Android, Windows

Affected platform versions

Windows 11, Android 12 (API 31)

Did you find any workaround?

Avoid using DI for App class. Instead, create a service locator in your app and use the Service Locator pattern in the MainPage constructor to get all the dependencies.

Relevant log output

No response

ghost commented 1 year ago

We've added this issue to our backlog, and we will work to address it as time and resources allow. If you have any additional information or questions about this issue, please leave a comment. For additional info about issue management, please read our Triage Process.

XamlTest commented 1 year ago

Verified this on Visual Studio Enterprise 17.7.0 Preview 2.0. Repro on Windows 11, Android 13.0-API33 and iOS 16.4 with below Project: BrokenConstructor.zip

ThysBrits commented 6 months ago

This is still an issue, but is only visible if you run your app outside the debugger. If you run your app attached to the debugger, the error is not picked up. When will this be solved?