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:

  1. Create a class library “Plugin” using template “Class Library (WinUI 3 in Desktop)”

  2. Add a UserControl “PluginUserControl” using template “User Control (WinUI 3)” to Plugin.csproj

  3. Create an application “HostApp” using template “Black App, Packaged (WinUI 3 in Desktop)”

  4. 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;
            }
        }
    }
    
    
  5. 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");
            }
        }
    
  6. Build Plugin.csproj

  7. 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)

Most upvoted comments

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:

  • We are using WinUI 2.x Nuget with C++/WinRT in a UWP project.
  • Our plugins for the UI are based on the Windows Runtime Component (C++/WinRT) template
  • To make things easy on us (and our future users) we have created a custom nuget package which supplies our plugin SDK headers, DLLs and a build targets, which can deploy the plug-in and generate the MSIX package for it as well in a single Visual Studio project
  • We generate the plugin MSIX from command line using the MakeAppX.exe, SignTool.exe etc., note this requires some specific steps, for example for XAML you must make sure to have the package resource index (PRI) files also in the package (something I wasted some time on…), we are NOT using related sets
  • Our plug-ins have a single C export called Init over the regular winrt activation stuff, which receives a pointer to our dependency container implementation, in the method the plug-ins can resolve components from the dependency container and register their services, e.g. register a new XAML panel on our tool panel

And now the code snippets:

  • First we locate the plug-ins, which are in optional packages:
  PluginCollection PluginProviderBase::GetPluginPackages()
  {
    _logger.log(log_severity::info, L"Enumerating plug-ins...");
    auto dependencies = Package::Current().Dependencies();

    unordered_map<wstring, Package> results;
    for (const auto& dependency : dependencies)
    {
      if (dependency.IsFramework() || !dependency.IsOptional()) continue;

      auto pluginId = wstring(dependency.Id().FamilyName());
      results.emplace(pluginId, dependency);
      _logger.log(log_severity::info, L"Plug-in detected: %s", dependency.DisplayName().c_str());
    }

    return results;
  }
  • Then if a plug-in is selected we load it:
  bool PluginProviderBase::TryLoadPlugin(const std::wstring& pluginId)
  {
    if (_loadedPlugins.count(pluginId)) return true;

    try
    {
      //Check if the plugin exists
      auto pluginPackageIt = _availablePlugins.find(pluginId);
      if (pluginPackageIt == _availablePlugins.end()) throw runtime_error("The specified plug-in package does not exist.");

      //Locate plug-in DLL
      auto pluginPackage = pluginPackageIt->second;
      auto packageFolder = pluginPackage.InstalledLocation();
      auto pluginLibraryPath = packageFolder.Path() + L"\\" + pluginPackage.Id().Name() + L".dll";

      //Load plugin DLL
      AddDllDirectory(packageFolder.Path().c_str());
      auto pluginLibrary = LoadLibrary(pluginLibraryPath.c_str());
      if (!pluginLibrary) throw_last_error();

      //Initialize plug-in
      InitializePlugin(pluginId, pluginLibrary);

      return true;
    }
    catch (const hresult_error& error)
    {
      _logger.log(log_severity::error, L"Failed to load plug-in %s: %s", pluginId.c_str(), error.message().c_str());
    }
    catch (const exception& error)
    {
      _logger.log(log_severity::error, L"Failed to load plug-in %s: %s", pluginId.c_str(), to_wstring(error.what()).c_str());
    }
    catch (...)
    {
      _logger.log(log_severity::error, L"Failed to load plug-in %s: unknown error.", pluginId.c_str());
    }

    return false;
  }
  • Then we initialize our plug-in - here you can see how we instantiate the XamlMetadataProvider of the plug-in, which is generated by the WinRT tooling when XAML controls are present in the runtime component:
  void PluginProvider::InitializePlugin(const wstring& /*pluginId*/, HMODULE pluginLibrary)
  {
    //Load Xaml Metadata
    wstring filePath;
    filePath.resize(256);
    GetModuleFileNameW(pluginLibrary, filePath.data(), DWORD(filePath.length()));

    auto libraryName = path(filePath).filename().replace_extension();
    auto metadataFactory = try_get_activation_factory(libraryName + L".XamlMetaDataProvider");
    if (metadataFactory)
    {
      auto metadataProvider = metadataFactory.ActivateInstance<IXamlMetadataProvider>();
      PluginXamlMetadataProvider::MetadataProviders().Append(metadataProvider);
    }

    //Initialize plug-in
    auto initializer = PluginInitializer(GetProcAddress(pluginLibrary, "Init"));
    if (!initializer) throw runtime_error("Failed to find plug-in initializer method.");

    auto container = _dependencyContainerReference.try_lock();
    if (!container) throw runtime_error("The dependency container is not available.");
    
    initializer(container.get());
  }
  • We then implemented a class PluginXamlMetadataProvider, which inherits from IXamlMetadataProvider - this class is however not in the main executable project, but in another windows runtime component one, which is referenced by the main project, this trigger the WinRT tooling to find it and use it for resolving namespaces in XAML code:
  [default_interface]
  runtimeclass PluginXamlMetadataProvider : Windows.UI.Xaml.Markup.IXamlMetadataProvider
  {
    PluginXamlMetadataProvider();

    static IVector<Windows.UI.Xaml.Markup.IXamlMetadataProvider> MetadataProviders{ get; };
  }
  IVector<IXamlMetadataProvider> PluginXamlMetadataProvider::_metadataProviders = single_threaded_vector<IXamlMetadataProvider>();

  IXamlType PluginXamlMetadataProvider::GetXamlType(TypeName const& type)
  {
    for (const auto& provider : _metadataProviders)
    {
      auto xamlType = provider.GetXamlType(type);
      if (xamlType) return xamlType;
    }

    return nullptr;
  }

  IXamlType PluginXamlMetadataProvider::GetXamlType(hstring const& fullName)
  {
    for (const auto& provider : _metadataProviders)
    {
      auto xamlType = provider.GetXamlType(fullName);
      if (xamlType) return xamlType;
    }

    return nullptr;
  }

  com_array<XmlnsDefinition> PluginXamlMetadataProvider::GetXmlnsDefinitions()
  {
    vector<XmlnsDefinition> xmlnsDefinitions;
    for (const auto& provider : _metadataProviders)
    {
      auto definitions = provider.GetXmlnsDefinitions();
      for (auto& definition : definitions)
      {
        xmlnsDefinitions.push_back(definition);
      }
    }

    return { xmlnsDefinitions.begin(), xmlnsDefinitions.end() };
  }

  IVector<IXamlMetadataProvider> PluginXamlMetadataProvider::MetadataProviders()
  {
    return _metadataProviders;
  }
  • The above will cause the std::vector<::winrt::Windows::UI::Xaml::Markup::IXamlMetadataProvider> const& XamlTypeInfoProvider::OtherProviders() method to add PluginXamlMetadataProvider to 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:

#define InitializePluginComponent(component_t) { if (!_contentLoaded) { _contentLoaded = true; winrt::Windows::Foundation::Uri resourceLocator{ L"ms-appx://TestLibrary/TestLibrary/" L#component_t L".xaml" }; winrt::Windows::UI::Xaml::Application::LoadComponent(*this, resourceLocator, winrt::Windows::UI::Xaml::Controls::Primitives::ComponentResourceLocation::Nested); } }

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:

  • First you need to use a custom InitializeComponent() implementation, so you specify your package name in the path as described above
  • In addition you need implement a IXamlMetadataProvider interface, and inside it you need to redirect the calls to your custom DLL’s XamlMetadataProvider classes, which you can instantiate with reflection or winrt::create_instance, as they are autogenerated classes their name is known. This implementation is autodetected by tooling and invoked when namespaces and types are resolved in XAML.

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 GetXamlType is getting called from the native Xaml interop with a null type 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

@axodox Would you mind providing some example code showing how you went about this?

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.

We seem to have found a workaround which allows this to work, it requires two basic things:

  • First you need to use a custom InitializeComponent() implementation, so you specify your package name in the path as described above
  • In addition you need implement a IXamlMetadataProvider interface, and inside it you need to redirect the calls to your custom DLL’s XamlMetadataProvider classes, which you can instantiate with reflection or winrt::create_instance, as they are autogenerated classes their name is known. This implementation is autodetected by tooling and invoked when namespaces and types are resolved in XAML.

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.

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:

  • Rename the file to resources.pri and put it in the root of the msix
  • Create a package mapping file with a [ResourceMetadata] section
  • Make sure that the tooling processed xaml files are also added to the msix under the directory named as target name
  • Use makeappx.exe to pack the files with the mapping

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: plugin resource map loaded 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:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PriInfo>
	<PriHeader>
		<WindowsEnvironment name="WinCore" version="1.2" checksum="1912541329"/>
		<AutoMerge>false</AutoMerge>
		<IsDeploymentMergeable>true</IsDeploymentMergeable>
		<TargetOS version="10.0.0"/>
		<ReverseMap>false</ReverseMap>
	</PriHeader>
	<QualifierInfo>
		<Qualifiers>
			<Qualifier name="Language" value="EN-US" priority="700" scoreAsDefault="1.0" index="1"/>
		</Qualifiers>
		<QualifierSets>
			<QualifierSet index="1">
				<Qualifier name="Language" value="EN-US" priority="700" scoreAsDefault="1.0" index="1"/>
			</QualifierSet>
		</QualifierSets>
		<Decisions>
			<Decision index="2">
				<QualifierSet index="1">
					<Qualifier name="Language" value="EN-US" priority="700" scoreAsDefault="1.0" index="1"/>
				</QualifierSet>
			</Decision>
		</Decisions>
	</QualifierInfo>
	<ResourceMap name="HostApp.SimplePlugin" primary="true" uniqueName="ms-appx://HostApp.SimplePlugin/" version="1.0">
		<VersionInfo version="1.0" checksum="1169589394" numScopes="16" numItems="15"/>
		<ResourceMapSubtree index="1" name="Files">
			<ResourceMapSubtree index="15" name="HostApp.SimplePlugin">
				<NamedResource name="SimpleUI.xbf" index="14" uri="ms-resource://HostApp.SimplePlugin/Files/HostApp.SimplePlugin/SimpleUI.xbf">
					<Decision index="1">
						<QualifierSet index="0"/>
					</Decision>
					<Candidate type="Path">
						<QualifierSet index="0"/>
						<Value>HostApp.SimplePlugin\SimpleUI.xbf</Value>
					</Candidate>
				</NamedResource>
			</ResourceMapSubtree>
		</ResourceMapSubtree>
	</ResourceMap>
</PriInfo>

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.