語言
.NET Generic Host 提供一套標準化的方式來配置與執行應用程式,並內建相依注入(DI)、設定與日誌記錄。 WPF 應用程式預設不包含主機建構器整合,但你可以新增。 本文說明如何在 WPF 應用程式中設定通用主機,將服務注入 Windows 並使用完整的 .NET 主機架構。
先決條件
-
Microsoft.Extensions.HostingNuGet 套件。
建立通用主機
要將通用主機整合到你的 WPF 應用程式中:
從應用程式的 XAML 檔案中移除
StartupUri,並接線StartupExit事件處理程式:<Application x:Class="HostBuilderApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Startup="Application_Startup" Exit="Application_Exit"> <Application.Resources> </Application.Resources> </Application>在後置程式碼中建置主機。
此方法使用
Application_Startup建立主機,將CreateApplicationBuilder服務註冊於Services屬性,啟動主機,並顯示主視窗。private async void Application_Startup(object sender, StartupEventArgs e) { var builder = Host.CreateApplicationBuilder(); builder.Services.AddHostedService<SampleLifecycleService>(); builder.Services.AddSingleton<IGreetingService, GreetingService>(); builder.Services.AddSingleton<MainWindow>(); _host = builder.Build(); await _host.StartAsync(); MainWindow mainWindow = _host.Services.GetRequiredService<MainWindow>(); mainWindow.Show(); }Private Async Sub Application_Startup(sender As Object, e As StartupEventArgs) Dim builder = Host.CreateApplicationBuilder() builder.Services.AddHostedService(Of SampleLifecycleService)() builder.Services.AddSingleton(Of IGreetingService, GreetingService)() builder.Services.AddSingleton(Of MainWindow)() _host = builder.Build() Await _host.StartAsync() Dim mainWindow As MainWindow = _host.Services.GetRequiredService(Of MainWindow)() mainWindow.Show() End Sub當應用程式退出以清理資源時,停止並丟棄主機:
private async void Application_Exit(object sender, ExitEventArgs e) { using (_host) { await _host.StopAsync(); } }Private Async Sub Application_Exit(sender As Object, e As ExitEventArgs) Using _host Await _host.StopAsync() End Using End Sub
建立服務
前一節的 Services 屬性是用 DI 容器來登記服務。 要建立自訂服務:
定義服務介面:
public interface IGreetingService { string GetGreeting(); }Public Interface IGreetingService Function GetGreeting() As String End Interface建立一個實作介面的類別。 該
GreetingService類別透過建構子注入 IConfiguration,以便從appsettings.json讀取值:public class GreetingService(IConfiguration configuration) : IGreetingService { public string GetGreeting() => configuration.GetValue<string>("GreetingMessage") ?? "Hello from the Generic Host!"; }Public Class GreetingService Implements IGreetingService Private ReadOnly _configuration As IConfiguration Public Sub New(configuration As IConfiguration) _configuration = configuration End Sub Public Function GetGreeting() As String Implements IGreetingService.GetGreeting Dim message As String = _configuration.GetValue(Of String)("GreetingMessage") If String.IsNullOrEmpty(message) Then Return "Hello from the Generic Host!" End If Return message End Function End Class
運行託管服務
Generic Host 也能執行參與應用程式生命週期的背景服務。 主機在開始和停止時會呼叫 IHostedService 的實作。 要新增託管服務:
建立會實作 IHostedService 的類別。 當主機開始與停止時,以下類別會寫入除錯輸出:
public class SampleLifecycleService : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { System.Diagnostics.Debug.WriteLine("SampleLifecycleService: Started."); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { System.Diagnostics.Debug.WriteLine("SampleLifecycleService: Stopped."); return Task.CompletedTask; } }Public Class SampleLifecycleService Implements IHostedService Public Function StartAsync(cancellationToken As CancellationToken) As Task Implements IHostedService.StartAsync System.Diagnostics.Debug.WriteLine("SampleLifecycleService: Started.") Return Task.CompletedTask End Function Public Function StopAsync(cancellationToken As CancellationToken) As Task Implements IHostedService.StopAsync System.Diagnostics.Debug.WriteLine("SampleLifecycleService: Stopped.") Return Task.CompletedTask End Function End Class請在生成器
AddHostedService的Services屬性中註冊此服務,如設定通用主機部分中的Application_Startup方法所示。
主機在開始和StartAsync停止時呼叫StopAsync,因此除錯輸出會出現在 Visual Studio 的輸出視窗中。
將服務注入視窗
DI 容器透過建構器注入,將相依性注入到已註冊的視窗中。 在視窗內消費服務:
- 為每個視窗所需的服務新增建構參數。
- 將注射服務儲存在私人田地。
- 在事件處理程式或其他方法中使用這些服務。
以下程式碼顯示 MainWindow 接受 ILogger<MainWindow> 並 IGreetingService 通過其構造子:
public partial class MainWindow : Window
{
private readonly ILogger<MainWindow> _logger;
private readonly IGreetingService _greetingService;
public MainWindow(ILogger<MainWindow> logger, IGreetingService greetingService)
{
InitializeComponent();
_logger = logger;
_greetingService = greetingService;
}
private void OnGetGreetingClick(object sender, RoutedEventArgs e)
{
_logger.LogInformation("Get Greeting button clicked.");
GreetingText.Text = _greetingService.GetGreeting();
}
}
Class MainWindow
Private ReadOnly _logger As ILogger(Of MainWindow)
Private ReadOnly _greetingService As IGreetingService
Public Sub New(logger As ILogger(Of MainWindow), greetingService As IGreetingService)
InitializeComponent()
_logger = logger
_greetingService = greetingService
End Sub
Private Sub OnGetGreetingClick(sender As Object, e As RoutedEventArgs)
_logger.LogInformation("Get Greeting button clicked.")
GreetingText.Text = _greetingService.GetGreeting()
End Sub
End Class
新增組態
當檔案在輸出目錄時,CreateApplicationBuilder 會自動載入 appsettings.json。 要為你的專案新增設定檔:
在專案根建立
appsettings.json一個包含你的設定值的檔案:{ "GreetingMessage": "Hello from the .NET Generic Host!" }在專案檔案中設定
CopyToOutputDirectory為 ,PreserveNewest使檔案能複製到輸出目錄:<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>WinExe</OutputType> <TargetFramework>net10.0-windows</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <UseWPF>true</UseWPF> </PropertyGroup> <ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.*" /> </ItemGroup> </Project>