.NET Core 3.0 in WPF use of graphic tutorials IOC

This article is mainly to introduce the graphic tutorial on using the IOC in .NET Core 3.0 in WPF, the paper sample code described in great detail, has a certain reference value of learning for all of us to learn or work, you need the following friends come together to learn from it

Foreword

We all know .NET Core 3.0 has released a preview version of the sixth, we also know that .NET Core 3.0 now supports creating WPF project, and today just writing a code generator when a client uses WPF, so put WPF to create and use a process IOC recording it, I hope you can help. Of course I will take the example of article sample code I have read an article to be demonstrated.

step

1, create a wpf project through the command line, you can of course also be created using vs2019. Not demonstrate the concrete steps, of course, if you do not use vs2019 create a project, then you close the upper right corner of the page, province of 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\3.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

  

We want to achieve is to guide the application and inject a service in the constructor of MainWindow, the service will be invoked to display some text on the main window of the application.

2, we preferred Microsoft Extensions to be installed under DependencyInjectionnuget package, of course, you can also add the following way, but the best introduction to the latest preview version by nuget way.

<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 a ITextService interface service, this interface is injected into the vessel by injection MainWindow dependency class for use.

public interface ITextService
{
  string GetText();
}

4, of course, you have to create a TextService class that implements the above interfaces.

class TextService : ITextService
{
  private string _text;
 
  public TextService(string text)
  {
    _text = text;
  }
 
  public string GetText()
  {
    return _text;
  }
}

5, the next entry in our configuration file in our App.xaml.cs IOC container, and check our services, I believe you have done .NET Core project, the following code should all be very familiar with, but here it is much to explain, provincial waste our valuable 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, then we rewrite OnStartup App.xaml.cs method, parse out and show it MainWindow

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

Of course, this means you have to remove the boot options App.xmal the following code:

<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, then we modify Code xaml MainWindow in order to show our text message:

<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 MainWindow cs of the code should be adjusted, the method to be able to accept incoming IOC injection.

public partial class MainWindow : Window
{
  public MainWindow(ITextService textService)
  {
    InitializeComponent();
 
    Label.Content = textService.GetText();
  }
}

 

result

I believe cumbersome steps above you have read, then the next step is to witness the miracle of the moment, and open your eyes and offer a beautiful picture:

As shown above: MainWindow incoming call IOC injection TextService service and correctly displays text.

 

Guess you like

Origin www.cnblogs.com/jb1352461/p/11126817.html