How can we get Microsoft's dependency Injection to resolve dependencies within razor files referenced using Microsoft's BlazorWebView within a WPF app?

Owsen, Craig 21 Reputation points
2022-12-11T18:34:53.333+00:00

I am using Microsoft.Extenssions.DependencyInjection to resolve dependencies. I am able to successfully inject dependencies into the MainWindow (I am keeping the scenario simple). But when I reference a razor file with dependencies using BlazorWebView, I cannot get the dependencies resolved. These razor files are from a Blazor Server app. If I remove all references to dependencies, I am able to access the Razor page. Microsoft Learn provides a simple implementation of BlazorWebViews within a WPF App: "Build a Windows Presentation Foundation (WPF) Blazor app", but the razor page referenced is a simple counter with no dependencies. I can get that to work! I even added a transient service referencing the Razor page . I have got the MAUI Blazor Windows Desktop working - but that requires certificates - which small to medium size companies don't need or can afford. So the only remaining option is BlazorWebViews!

Developer technologies Windows Presentation Foundation
Developer technologies .NET Blazor
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2022-12-12T08:10:42.15+00:00

    Hi @Owsen, Craig ,

    To inject the dependency service in the Raozr files, you need to register these services in the MainWindow.xaml.cs file.

    For example, according to the Build a Windows Presentation Foundation (WPF) Blazor app, I create a WPF aplication, and then add a IDataRepository service like this:

    269596-image.png

    In the MainWindow.xaml.cs file, register the service:

    public MainWindow()  
    	{  
    		InitializeComponent();  
    
            var serviceCollection = new ServiceCollection();  
            serviceCollection.AddWpfBlazorWebView();  
    		serviceCollection.AddTransient<IDataRepository, DataRepository>();  //register the service  
            Resources.Add("services", serviceCollection.BuildServiceProvider());  
        }  
    

    After that in the Counter.cshtml page, we can inject the Service:

    269529-image.png

    And the result as below:

    269615-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.