IOC graphic tutorial in using the 3.0 WPF .NET Core in

Original: Use IOC graphic tutorials in the 3.0 WPF .NET Core in

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.

Author: according to Le Wish

Original link: https://www.cnblogs.com/yilezhu/p/11099358.html

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 to be installed next Microsoft Extensions 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. Creating a ITextServiceservice interface, this interface will be injected into dependency injection container MainWindowclass for use.

    public interface ITextService
    {
        string GetText();
    }
  4. Of course, you have to create a TextServiceclass that implements the above interfaces.

    class TextService : ITextService
    {
        private string _text;
    
        public TextService(string text)
        {
            _text = text;
        }
    
        public string GetText()
        {
            return _text;
        }
    }
  5. In our next entry App.xaml.csin the configuration file of our IOC container, and check our service, did you believe .NET Core project, the underlying code should be very familiar with, there is not too much to explain, and the province 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. Next we rewrite App.xaml.csthe OnStartupmethod, parse out MainWindowand show it

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 App.xmalboot options, 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 MainWindowthe code so that xaml 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, MainWindowthe codes should be adjusted under cs, to a method capable of accepting 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: MainWindowcall incoming IOC injection TextServiceservice and correctly displays text.

Thankfully, not a bug, in fact I would say that this picture to be lazy, I have been stolen, the end of the text on the original link.

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

At last

More recent things, no time to properly share the article. Of course, whenever I retired and sit to learn and I will be sharing with the corresponding summary. Just busy work reasons, more and more low frequency only.

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11105754.html