A Complete Guide - .NET MAUI Using DependencyService and IPlatformService

Last Updated: 03 Jul, 2025   
  YOU NEED ANY HELP? THEN SELECT ANY TEXT.

.NET MAUI Using DependencyService and IPlatformService

DependencyService Overview

DependencyService is a service locator that simplifies the process of instantiating platform-specific classes that adhere to a shared interface. This approach allows developers to write platform-agnostic code while still accessing platform-specific features.

Key Tasks of DependencyService

  • Interface Definition: Define an interface in the shared project that outlines the methods you want to implement in platform-specific projects.
  • Implementation: Implement the interface in each platform project.
  • Resolution: Use DependencyService.Register<T>() to register services and DependencyService.Get<T>() to resolve them.

Example Usage

  1. Define an Interface in Shared Project
public interface IToast
{
    void MakeToast(string message);
}
  1. Implement Interface on iOS
using UserNotifications;
using Foundation;

[assembly: Xamarin.Forms.Dependency(typeof(Toast_iOS))]
public class Toast_iOS : IToast
{
    public void MakeToast(string message)
    {
        var notification = new UNMutableNotificationContent();
        notification.Title = "Note:";
        notification.Body = message;

        var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);
        var request = UNNotificationRequest.FromIdentifier("toast", notification, trigger);
        UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
            if (err != null)
                Console.WriteLine(err.LocalizedDescription);
        });
    }
}
  1. Implement Interface on Android
using Android.Widget;
using Xamarin.Forms;

[assembly: Dependency(typeof(Toast_Droid))]
public class Toast_Droid : IToast
{
    public void MakeToast(string message)
    {
        Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short).Show();
    }
}
  1. Resolve Interface in Shared Code
public void ShowToast(string message)
{
    DependencyService.Get<IToast>().MakeToast(message);
}

IPlatformService Overview

IPlatformService is a newer addition in .NET 7, designed to provide a practical framework for accessing platform-specific features with enhanced type safety and maintainability. Unlike DependencyService, IPlatformService offers a more streamlined approach by leveraging HRESULTs and easier-to-read method signatures.

Key Features of IPlatformService

  • Strongly Typed: Methods return strongly-typed results, reducing errors related to loose typing.
  • Error Handling: Supports more robust error handling through HRESULTs.
  • Modern API: Follows modern .NET patterns and best practices.

Example Usage

  1. Define an Interface Using IPlatformService

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement .NET MAUI Using DependencyService and IPlatformService


Prerequisites

  1. .NET MAUI Installed: Ensure you have the latest version of .NET MAUI installed in your Visual Studio.
  2. Basic Knowledge: Familiarity with C#, XAML, and .NET MAUI is helpful.

Step 1: Create a New .NET MAUI Project

  1. Open Visual Studio.
  2. Create a New Project:
    • Go to File > New > Project.
    • Select MAUI App (.NET 6+/.NET Standard 2.0).
    • Click Next.
  3. Configure the Project:
    • Enter your project name, e.g., MauiDependencyServiceExample.
    • Choose a location and click Create.
  4. Solution Structure:
    • Your solution will contain platform-specific projects (e.g., MauiDependencyServiceExample.Android, MauiDependencyServiceExample.iOS, etc.).

Step 2: Define the Interface IPlatformService

Create an interface that will define the platform-specific functionality you want to expose. In this example, we'll create a simple service to show a platform-specific message.

  1. Add a New Interface:
    • Right-click on the MauiDependencyServiceExample (Shared) project.
    • Go to Add > New Item.
    • Select Interface and name it IPlatformService.cs.
  2. Define the Method:
    using System.Threading.Tasks;
    
    namespace MauiDependencyServiceExample
    {
        public interface IPlatformService
        {
            Task ShowPlatformMessage(string message);
        }
    }
    

Step 3: Implement IPlatformService for Android

  1. Add a New Class:
    • Navigate to the MauiDependencyServiceExample.Android project.
    • Right-click the project and select Add > New Item.
    • Choose Class and name it PlatformServiceAndroid.cs.
  2. Implement the Interface:
    using Android.App;
    using Android.Widget;
    using MauiDependencyServiceExample;
    using System.Threading.Tasks;
    
    [assembly: Xamarin.Forms.Dependency(typeof(PlatformServiceAndroid))]
    namespace MauiDependencyServiceExample.Droid
    {
        public class PlatformServiceAndroid : IPlatformService
        {
            public Task ShowPlatformMessage(string message)
            {
                RunOnUiThread(() =>
                {
                    Toast.MakeText(Application.Context, message, ToastLength.Short).Show();
                });
                return Task.CompletedTask;
            }
    
            private void RunOnUiThread(Action action)
            {
                Application.SynchronizationContext.Post(_ => action?.Invoke(), null);
            }
        }
    }
    

Step 4: Implement IPlatformService for iOS

  1. Add a New Class:
    • Navigate to the MauiDependencyServiceExample.iOS project.
    • Right-click the project and select Add > New Item.
    • Choose Class and name it PlatformServiceiOS.cs.
  2. Implement the Interface:
    using MauiDependencyServiceExample;
    using UIKit;
    using System.Threading.Tasks;
    
    [assembly: Xamarin.Forms.Dependency(typeof(PlatformServiceiOS))]
    namespace MauiDependencyServiceExample.iOS
    {
        public class PlatformServiceiOS : IPlatformService
        {
            public Task ShowPlatformMessage(string message)
            {
                UIKit.UIThread.RunBackground(() =>
                {
                    UIKit.UIThread.RunOnMain(() =>
                    {
                        var alertController = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);
                        alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                        UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alertController, true, null);
                    });
                });
                return Task.CompletedTask;
            }
        }
    }
    

Step 5: Use DependencyService in the Shared Code

Now, let's use DependencyService to invoke the platform-specific method from the shared code.

  1. Modify MainPage.xaml:

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="
                 xmlns:x="
                 x:Class="MauiDependencyServiceExample.MainPage"
                 Title="Maui DependencyService Example">
    
        <StackLayout Padding="20">
            <Label Text="Welcome to Maui!" 
                   HorizontalTextAlignment="Center" 
                   FontSize="24" 
                   Margin="0,0,0,20"/>
    
            <Button Text="Show Platform Message" 
                    Clicked="OnShowPlatformMessageClicked" 
                    HorizontalOptions="CenterAndExpand" 
                    BackgroundColor="#007AFF" 
                    TextColor="White"/>
        </StackLayout>
    </ContentPage>
    
  2. Modify MainPage.xaml.cs:

    using MauiDependencyServiceExample;
    using Microsoft.Maui.Controls;
    using System.Threading.Tasks;
    
    namespace MauiDependencyServiceExample
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
            }
    
            private async void OnShowPlatformMessageClicked(object sender, System.EventArgs e)
            {
                // Resolve the platform-specific service
                var platformService = DependencyService.Get<IPlatformService>();
    
                // Invoke the platform-specific method
                await platformService.ShowPlatformMessage("Hello from .NET MAUI!");
            }
        }
    }
    

Step 6: Run the Application

  1. Select a Platform: Choose the platform you want to run the app on (e.g., Android, iOS).
  2. Deploy the App:
    • Android: Connect an Android device or use an emulator.
    • iOS: Use a Mac with Xcode or an iPhone/iPad.
  3. Run the App: Click the green play button in Visual Studio.

Expected Output:

  • Android: A toast message saying "Hello from .NET MAUI!" will appear.
  • iOS: An alert dialog with the message "Hello from .NET MAUI!" will be displayed.

Summary

You have successfully created a .NET MAUI application that uses DependencyService to invoke platform-specific functionality through an interface (IPlatformService). This approach allows you to write shared code while accessing native capabilities on each platform.


Additional Resources

  • Xamarin.Forms DependencyService Documentation
  • .NET MAUI Documentation
  • Xamarin.Forms vs .NET MAUI Comparison

You May Like This Related .NET Topic

Login to post a comment.