7.5Using in MAUI Applications
.NET MAUI has built-in dependency injection support based on Microsoft.Extensions.DependencyInjection: register services on builder.Services in the app entry point MauiProgram.CreateMauiApp(), then inject and use them through the constructors of pages (Page) or view models (ViewModel). For more details about dependency injection (registration approaches, service lifetimes, etc.), see the official Microsoft documentation "Dependency injection in .NET MAUI".
1. Register the service in MauiProgram.cs
Call AddHttpRemote() in the CreateMauiApp() method of MauiProgram.cs to register the HTTP remote request service:
using HttpAgent;public static class MauiProgram{ 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.AddHttpRemote(); // register the HTTP remote request service return builder.Build(); }}2. Inject and use it in a page
Inject IHttpRemoteService through the constructor of a page (or a view model) to send HTTP remote requests:
using HttpAgent;public partial class MainPage : ContentPage{ private readonly IHttpRemoteService _httpRemoteService; public MainPage(IHttpRemoteService httpRemoteService) { InitializeComponent(); _httpRemoteService = httpRemoteService; } private async Task LoadContentAsync() { var result = await _httpRemoteService.GetAsStringAsync("https://furion.net/"); // render result ... }}Note: in
Shellapplications, if a page's constructor needs dependency injection, register the page with the container as well (e.g.builder.Services.AddTransient<MainPage>();) soShellnavigation can resolve the page instance from the container; alternatively, injectIHttpRemoteServiceinto a registered view model and inject that view model into the page.