Graphic tutorial of using IOC in WPF in. Net core 3.0

Time:2020-6-27

preface

We all know that. Net core 3.0 has released the sixth preview version. We also know that. Net core 3.0 now supports the creation of WPF projects. Today, WPF is used when writing a code generator client, so we will record the process of creating and Using WPF, hoping to help you. Of course, the article example I have read an article to demonstrate the example code.

step

1. WPF projects are created from the command line, but you can also create them from vs2019. The specific steps will not be demonstrated. Of course, if you are not able to create a project with vs2019, please close the web page in the upper right corner to save worry.


❯ mkdir WpfIoc
❯ cd WpfIoc
❯ dotnet.exe --version
3.0.100-preview6-012264

❯ dotnet new wpf
The template "WPF Application" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on C:\Users\laure\projects\WpfIoc\WpfIoc.csproj...
 Restore completed in 90.03 ms for C:\Users\laure\projects\WpfIoc\WpfIoc.csproj.

Restore succeeded.

❯ dotnet build
Microsoft (R) Build Engine version 16.1.54-preview+gd004974104 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

 Restore completed in 19.92 ms for C:\Users\laure\projects\WpfIoc\WpfIoc.csproj.
C:\Program Files\dotnet\sdk.0.100-preview6-012264\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.RuntimeIdentifierInference.targets(151,5): message NETSDK1057: You are using a preview version of .NET Core. See: https://aka.ms/dotnet-core-preview [C:\Users\laure\projects\WpfIoc\WpfIoc.csproj]
 WpfIoc -> C:\Users\laure\projects\WpfIoc\bin\Debug\netcoreapp3.0\WpfIoc.dll

Build succeeded.
  0 Warning(s)
  0 Error(s)

Time Elapsed 00:00:01.63

What we want to implement is to boot the application and inject a service into the constructor of MainWindow, which will be called to display some text on the main window of the application.

2. We prefer to install the Microsoft extensions dependencyinjectionnuget package. Of course, you can add it in the following way, but it’s better to introduce the latest preview version through nuget.


<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

 <PropertyGroup>
  <OutputType>WinExe</OutputType>
  <TargetFramework>netcoreapp3.0</TargetFramework>
  <UseWPF>true</UseWPF>
 </PropertyGroup>

 <ItemGroup>
  <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0-preview6.19304.6" />
 </ItemGroup>

 <ItemGroup>
  <ProjectReference Include="..\StoneGenerate.Core\StoneGenerate.Core.csproj" />
 </ItemGroup>

</Project>

3. Create an itextservice interface service, which will be injected into the MainWindow class by the dependency injection container.


public interface ITextService
{
  string GetText();
}

4. Of course, you have to create a textservice class to implement the above interface.


class TextService : ITextService
{
  private string _text;

  public TextService(string text)
  {
    _text = text;
  }

  public string GetText()
  {
    return _text;
  }
}

5. Next at our entrance App.xaml.cs Configure our IOC container in the file, and check in our service. I believe that you who have done the. Net core project should be very familiar with the following code. There are only a lot of explanations here, saving your precious time.


public App()
{
  var serviceCollection = new ServiceCollection();
  ConfigureServices(serviceCollection);

  _serviceProvider = serviceCollection.BuildServiceProvider();
}

private void ConfigureServices(IServiceCollection services)
{
  services.AddSingleton<ITextService>(provider => new TextService("Hi WPF .NET Core 3.0"));
  services.AddSingleton<MainWindow>();
}

6. Let’s rewrite it App.xaml.cs Onstartup method of, parse out MainWindow and show it


protected override void OnStartup(StartupEventArgs e)
    {
      base.OnStartup(e);
      var main = serviceProvider.GetRequiredService<MainWindow>();
      main.Show();
    }

Of course, that means you have to remove it App.xmal The code of the startup option in is as follows:


<Application x:Class="wpfioc.App"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:local="clr-namespace:wpfioc"
       Startup="App_OnStartup">
  <Application.Resources>
  </Application.Resources>
</Application>

1. Next, we modify the XAML code of MainWindow to display our text information:


<Window x:Class="WpfIoc.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfIoc"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="9*" />
      <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <Label Name="Label" Content="Hello .NET Core!" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="40" />
  </Grid>
</Window>

2. Of course, the CS code of MainWindow should also be adjusted to accept the method injected by IOC.


public partial class MainWindow : Window
{
  public MainWindow(ITextService textService)
  {
    InitializeComponent();

    Label.Content = textService.GetText();
  }
}

result

I believe you have seen all the complicated steps above. Then it’s time to witness the miracle. Open your eyes and present a beautiful picture:

As shown in the figure above: MainWindow calls the textservice service injected by IOC and displays the text correctly.

Thank goodness, there is no bug. In fact, I want to say that this picture is stolen for the sake of laziness. The original link is at the end of the article.

https://laurentkempe.com/2019/04/18/WPF-and-IOC-on-NET-Core-3-0/

last

Recently, there are so many things that I don’t have time to share articles. Of course, when I am free, I will summarize what I have learned and share it. It’s just that the frequency of work is getting lower and lower.

Well, that’s all the content of this article. I hope that the content of this article has a certain reference learning value for your study or work. Thank you for your support for developpaer.