3

【C#/.NET】MAUI上的依赖注入 - 欲东

 1 year ago
source link: https://www.cnblogs.com/xuyd/p/17517620.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

        在移动应用开发中,依赖注入是一项非常重要的技术,它可以帮助我们简化代码结构、提高可维护性并增加测试覆盖率。在最新的.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>
3171097-20230630184457230-291691325.gif
namespace QuickCalc.App.ViewModels;

public class LabelViewModel
{
    public string LabelText { get; set; } = "Hello World";
}
3171097-20230630184457230-291691325.gif

        我们通过依赖注入将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();
3171097-20230630184457230-291691325.gif

第一步安装Microsoft.Extensions.DependencyInjection

Install-Package Microsoft.Extensions.DependencyInjection
3171097-20230630184457230-291691325.gif

第二步打开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();
        }
3171097-20230630184457230-291691325.gif

        增加的两句服务注册

builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton<LabelViewModel>();
3171097-20230630184457230-291691325.gif

第三步修改App.xaml.cs

  public partial class App : Application
  {
      public App(MainPage mainPage)
      {
          InitializeComponent();

          MainPage = mainPage;
      }
  }
3171097-20230630184457230-291691325.gif

        增加了MainPage的构造函数注入

第四步修改MainPage.xaml.cs

 public partial class MainPage : ContentPage
 {

     public MainPage(LabelViewModel labelViewModel)
     {
         InitializeComponent();
         BindingContext = labelViewModel;
     }
 }
3171097-20230630184457230-291691325.gif

        增加了LabelViewModel的构造函数注入以及BindingContext的赋值。

第五步运行程序

        至此,运行项目可以看到hello,World!已经在MAUI中继承了依赖​3171097-20230630184457230-291691325.gif

        在MAUI上,依赖注入是一个非常有价值的技术,它可以帮助我们构建简洁、灵活和可测试的应用程序。通过合理地使用依赖注入,我们能够有效地管理和解耦组件之间的依赖关系,提高开发效率和代码质量。希望本文对您理解和应用MAUI上的依赖注入有所帮助!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK