什麼是集合類? 集合類的位置在System.Collections.Generic命名空間中。 在我看來,集合類和大學里《數據結構》中所學的各種結構很像。集合類中包含Queue<T>類、Stack<T>類,LinkedList<T>類,而《數據結構》中有隊列、棧、雙向鏈表。這些概念性的東西是想通的。 ...
引言
在移動應用開發中,依賴註入是一項非常重要的技術,它可以幫助我們簡化代碼結構、提高可維護性並增加測試覆蓋率。在最新的.NET跨平臺框架MAUI中,我們也可以利用依賴註入來構建高效的應用程式架構。本文將詳細介紹在MAUI上如何使用依賴註入,旨在幫助開發者更好地理解和應用這一技術。
什麼是依賴註入?
依賴註入是一種設計模式,它通過將對象的創建和依賴關係的管理交給容器來簡化應用程式的開發。依賴註入有助於解耦組件之間的依賴關係,使得代碼更加靈活、可擴展並且易於測試。
為什麼在MAUI上使用依賴註入?
在MAUI中,應用程式需要處理各種不同的服務、組件和資源,而這些依賴關係的管理可能會變得非常複雜。使用依賴註入可以有效地解耦這些依賴關係,使得我們能夠更加專註於應用程式的業務邏輯,而無需關註底層的實現細節。
如何在MAUI上使用依賴註入?
首先創建好一個.NET MAUI項目之後,需要有以下前提條件
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="QuickCalc.App.MainPage"> <Label VerticalTextAlignment="Center" HorizontalTextAlignment="Center" Text="{Binding LabelText}"/> </ContentPage>
namespace QuickCalc.App.ViewModels; public class LabelViewModel { public string LabelText { get; set; } = "Hello World"; }
我們通過依賴註入將LabelText屬性綁定到Label的Text上。
var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); }); #if DEBUG builder.Logging.AddDebug(); #endif return builder.Build();
第一步安裝Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.DependencyInjection
第二步打開MauiProgram.cs
public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); }); //服務註冊 builder.Services.AddSingleton<MainPage>(); builder.Services.AddSingleton<LabelViewModel>(); #if DEBUG builder.Logging.AddDebug(); #endif return builder.Build(); }
增加的兩句服務註冊
builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton<LabelViewModel>();
第三步修改App.xaml.cs
public partial class App : Application { public App(MainPage mainPage) { InitializeComponent(); MainPage = mainPage; } }
增加了MainPage的構造函數註入
第四步修改MainPage.xaml.cs
public partial class MainPage : ContentPage { public MainPage(LabelViewModel labelViewModel) { InitializeComponent(); BindingContext = labelViewModel; } }
增加了LabelViewModel的構造函數註入以及BindingContext的賦值。
第五步運行程式
至此,運行項目可以看到hello,World!已經在MAUI中繼承了依賴
結論
在MAUI上,依賴註入是一個非常有價值的技術,它可以幫助我們構建簡潔、靈活和可測試的應用程式。通過合理地使用依賴註入,我們能夠有效地管理和解耦組件之間的依賴關係,提高開發效率和代碼質量。希望本文對您理解和應用MAUI上的依賴註入有所幫助!