microsoft-ui-xaml: WinUI 3 Cant instantiate a UserControl from a location outside the application package or directory (XamlParseException)
Describe the bug
When instantiating a UserControl from outside the application package an XamlParseException is thrown from the UserControl constructor at this.InitializeComponent().
Exception thrown at 0x773B35D2 (KernelBase.dll) in HostApp.exe: WinRT originate error - 0x80004005 : 'Cannot locate resource from 'ms-appx:///Plugin/PluginUserControl.xaml'.'.
Exception thrown: 'Microsoft.UI.Xaml.Markup.XamlParseException' in WinRT.Runtime.dll
WinRT information: Cannot locate resource from 'ms-appx:///Plugin/PluginUserControl.xaml'.
XAML parsing failed.
Steps to reproduce the bug
See minimal reproducing repository https://github.com/williamfigtree/WinUIPluginIssue. Key steps to recreate:
-
Create a class library “Plugin” using template “Class Library (WinUI 3 in Desktop)”
-
Add a UserControl “PluginUserControl” using template “User Control (WinUI 3)” to Plugin.csproj
-
Create an application “HostApp” using template “Black App, Packaged (WinUI 3 in Desktop)”
-
Add the “PluginLoadContext” class from this tutorial https://docs.microsoft.com/en-us/dotnet/core/tutorials/creating-app-with-plugin-support to HostApp.csproj
using System; using System.Reflection; using System.Runtime.Loader; namespace HostApp { class PluginLoadContext : AssemblyLoadContext { private AssemblyDependencyResolver _resolver; public PluginLoadContext(string pluginPath) { _resolver = new AssemblyDependencyResolver(pluginPath); } protected override Assembly Load(AssemblyName assemblyName) { string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); if (assemblyPath != null) { return LoadFromAssemblyPath(assemblyPath); } return null; } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { string libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); if (libraryPath != null) { return LoadUnmanagedDllFromPath(libraryPath); } return IntPtr.Zero; } } } -
Add the following code to the App constructor. You may need to modify the path to Plugin.dll.
public App() { this.InitializeComponent(); // Attempt to load a UserControl from a plugin dll // PluginUserControl throws an XamlParsingExcpetion during instantiation // Locate plugin dll in the Plugin project bin directory var rootPath = Path.GetFullPath(@"..\..\..\..\..\..\..\..\", typeof(Program).Assembly.Location); var pluginDllPath = Path.Combine(rootPath, @"Plugin\bin\x86\Debug\net5.0-windows10.0.19041.0\Plugin.dll"); // Instantiate PluginUserControl var pluginLoadContext = new PluginLoadContext(pluginDllPath); using (pluginLoadContext.EnterContextualReflection()) { var pluginUserControl = Activator.CreateInstance("Plugin", "Plugin.PluginUserControl"); } } -
Build Plugin.csproj
-
Deploy and debug HostApp.csproj
Expected behavior
The UserControl is instantiated and the UserControl XAML resources supplied by the external project, package, or directory are located.
Screenshots
No response
NuGet package version
No response
Windows app type
- UWP
- Win32
Device form factor
Desktop
Windows version
November 2019 Update (18363)
Additional context
This is a blocking issue for applications which require plugins which supply their own UI.
Observed the issue with WinUI 3 1.0.0-preview3.
https://github.com/microsoft/microsoft-ui-xaml/issues/3888 describes a similar requirement but does not come to an appropriate solution as it requires files from the plugin to be copied into the main package. This prevents separate build and distribution of applications and plugins.
https://github.com/microsoft/microsoft-ui-xaml/issues/1365#issuecomment-534803147 and https://docs.microsoft.com/en-us/dotnet/core/tutorials/creating-app-with-plugin-support suggest that AssemblyLoadContext is the intended mechanism for plugin support and do not indicate any separate system for XAML resources.
About this issue
- Original URL
- State: open
- Created 5 years ago
- Reactions: 14
- Comments: 56 (4 by maintainers)
I have tried https://github.com/microsoft/microsoft-ui-xaml/issues/6299#issuecomment-1023856405 by @williamfigtree and it works for a single UserControl. However, if that UserControl contains another UserControl, then it fails.
So if you have a MainApp that tries to load a UserControlA from a AssemblyX, you would be able to load UserControlA as mentioned. However if there is another UserControlB in AssemblyX and UserControlA uses it in the XAML file, then we get XAML Parsing exception when loading the UserControlA. @RealTommyKlein do you have any suggestion or work around that you can think off.
Also, @marb2000 has mentioned that the WinUI team is concentrating on the core infrastructure this year, instead of adding more controls. Would you consider this issue/feature among core infrastructure tickets that needs to be addressed in 1.1 or 1.2? This issue is preventing us from developing a class of application (plugins with UIs). I am sure many others in the community too would like to see it addressed soon. @marb2000, @MikeHillberg, A guidance would help us immensely to determine the direction for our project.
So here is how we were able to load WinUI controls / converters from plug-ins:
First some notes:
And now the code snippets:
std::vector<::winrt::Windows::UI::Xaml::Markup::IXamlMetadataProvider> const& XamlTypeInfoProvider::OtherProviders()method to addPluginXamlMetadataProviderto the XAML metadata provider list in Generated Files\XamlTypeInfo.g.cpp.This allows the xaml namespaces to be resolved. You will still need the custom InitializeComponent method with the package name in the UI to make it work. I am not fond of macros, but maybe in this case it is OK:
Using the above you can build your app. And someone else can take your SDK and develop UI plug-ins which can be deployed without rebuilding the original app again.
We seem to have found a workaround which allows this to work, it requires two basic things:
Using the above two you will be able to load custom controls including xaml files which reference other custom controls, converters etc. This allows you to create lately discovered plug-ins, without related sets. So you can have a main app deployed, and you can make an optional package later which has UI and load it successfully in the app.
So basically this is already possible however it needs documentation, and the InitializeComponent code generation should be fixed so there is no need for a workaround.
Note we are using UWP + WinUI 2 with C++/WinRT, but maybe somebody can test this on WinUI 3 as well.
Hey, It would be cool to implement this functionality so we could directly design pages and views in xaml instead of using code behind C#
Do you have any plan to work on this issue ?
Thanks in advance
I’ve managed to get this working with some success in C#, however am still having problems where
GetXamlTypeis getting called from the native Xaml interop with anulltype argument if I reference certain things (like custom dependency properties using custom types). Best I can figure is that it is because the host apps PRI file doesn’t include references to the extension. I got it to work by merging the PRI files, but that isn’t a shippable solution for user-installed extensions.For reference, I have thrown a quick working library and example to do this in C#, and also does some special magic to keep hot reload working if your extension is not packaged with the application. (in my own use-case, I can launch the shipped host application with a cmdline argument pointing it at an extension output directory and have a lovely time with hot reload working 😃)
https://github.com/dnchattan/winui-extensions
Yes, but I have some other work to do now, so probably sometime next week.
@dnchattan Wanted to give a huge thanks to you (and all the others here). I was able to use your example to successfully get plugins working in our main app. I haven’t ran into any issues so far but will report in if I do.
That is very interesting! We will try it in Win UI 3 during tomorrow or next week. If you find the time to upload the examples, I would also be very interested in seeing it 😃 I will update in here with the results for Win UI 3.
I had problems at first with PRI as well with UWP / WinUI 2 / C++/WinRT. I had to do the following to fix it:
There is a tool which can dump your pri file to a human readable format, you can use it to make sure that it has all the content needed. I needed no modification in the code (except for the initialize component URI to have the package name) as discussed above. The runtime will locate the resources.pri in the package and load it, by default it has a different filename for me, which will not get loaded.
This way I could produce working plugins, including custom controls with custom dependency properties. Now we have it tested and working, the plugins are built after the main app from a separate git repo, so the main app has no knowledge of them.
@Pietro228 in addition to what axodox’s mentioned my repo has a powershell script that builds a WinUI 3 library as an optional package invoked from the post build target and a user control with the modified InitializeComponent code. None of it is beautiful but it might help you get started.
We would like this as well with C++/WinRT and XAML UI.
I discovered that I am able to successfuly load the UserControl if it is included in an optional package and the URI specifies the full path to the installed package location e.g.
ms-appx:///C:/Program Files/WindowsApps/[Package full name]/HostApp.SimplePlugin/SimpleUI.xaml.This is a viable workaround for simple things but leaves a big outstanding issue with resource location. Features like Resource.resw files and 3rd party controls with embedded xaml data do not work from the plugin package. So more on that:
@RealTommyKlein The plugin’s resources.pri file does seem to be loaded into the application’s resources although not into MainResourceMap. I can see this by inspecting AllResourceMaps on ResourceManager.Current at runtime:
Perhaps the plugin’s resources.pri is incorrect? I am using the resources.pri file that VisualStudio generates for a WinUI3 class library. Does it need to contain a named resource for the UserControl xaml and not the xbf? Is it formatted incorrectly? Here’s the plugin pri dump resources.pri.xml.zip and a trimmed down version with just the relevant resource map:
And here is the repo I’m using to test this with optional packages https://github.com/williamfigtree/WinUI3-plugin-sample. I’ve had to use a custom build script on the optional package project due to lack of VisualStudio tooling for WinUI3.