.NET Core 3.0中WPF使用IOC的图文教程

2022-10-16,,,,

前言

我们都知道.net core 3.0已经发布了第六个预览版,我们也知道.net core 3.0现在已经支持创建wpf项目了,刚好今天在写一个代码生成器的客户端的时候用到了wpf,所以就把wpf创建以及使用ioc的过程记录一下,希望能对大家有所帮助。当然文章实例我就以我曾阅读过的一篇文章的示例代码来进行演示了。

步骤

1、通过命令行创建wpf项目,当然你也可以通过vs2019来进行创建。具体的步骤就不演示了,当然,如果你还不会用vs2019创建项目,那么请你右上角关闭网页,省的烦心。

❯ 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

我们想要实现的是引导应用程序并在mainwindow的构造函数中注入一个服务,该服务将被调用以便在应用程序的主窗口上显示一些文本。

2、我们首选要安装下microsoft extensions dependencyinjectionnuget包,当然你也可以通过下面的方式进行添加,不过最好还是通过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、创建一个itextservice接口服务,这个接口将由依赖注入容器注入到mainwindow类中进行使用。

public interface itextservice
{
  string gettext();
}

4、当然你还得创建一个textservice类来实现上面的接口。

class textservice : itextservice
{
  private string _text;

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

  public string gettext()
  {
    return _text;
  }
}

5、接下来在我们的入口app.xaml.cs文件中配置我们的ioc容器,并入住我们的服务,相信做过.net core项目的你,对下面的代码应该都非常的熟悉,这里就不过多的解释了,省的浪费大家的宝贵时间。

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、接下来我们重写一下app.xaml.cs的onstartup方法,解析出mainwindow 并show出来

protected override void onstartup(startupeventargs e)
    {
      base.onstartup(e);
      var main = serviceprovider.getrequiredservice<mainwindow>();
      main.show();
    }

当然,这也就意味着你得移除app.xmal中的启动选项,代码如下:

<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、接下来我们修改一下mainwindow的xaml代码以便来显示我们的文本信息:

<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、当然,mainwindow的cs代码也要进行下调整,以便能够接受ioc注入进来的方法。

public partial class mainwindow : window
{
  public mainwindow(itextservice textservice)
  {
    initializecomponent();

    label.content = textservice.gettext();
  }
}

结果

相信上面的繁琐的步骤你也都看完了,那么接下来就是见证奇迹的时刻了,睁开你的双眼,奉上精美图片一张:

如上图所示:mainwindow调用了ioc注入进来的textservice服务并正确的显示了文字。

谢天谢地,没出bug,其实我想说,这张图为了偷懒,我都是盗的,文末上原文链接。

https://laurentkempe.com/2019/04/18/wpf-and-ioc-on-net-core-3-0/

最后

最近事情比较多,都没时间好好的分享文章了。当然,每当我闲下来的时候我就会对所学所用进行相应的总结后进行分享的。只是工作忙的原因,频次越来越低而已。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。

《.NET Core 3.0中WPF使用IOC的图文教程.doc》

下载本文的Word格式文档,以方便收藏与打印。