Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MAUI Dependency Injection in platform specific code

Is there any way to inject services in platform specific code, for example in MainActivity.cs? I think Xamarin used DependencyService for this. Also is it possible to inject them into background Services and Broadcast Receivers?

What I tried to do at the moment is newing them up but I wonder if there is a better solution at the moment. For what I understand, the DI container in platform specific code is not the same as the main one that you use in MauiProgram.cs, I've seen example where they implement one from scratch.

like image 425
ScottexBoy Avatar asked Mar 26 '26 18:03

ScottexBoy


2 Answers

I found this on Jame Montemagno's Youtube. I think this is what you are looking for. The video is here.

public static class ServiceHelper {

public static T GetService<T>() => Current.GetService<T>();

public static IServiceProvider Current =>
#if WINDOWS10_0_17763_0_OR_GREATER
    MauiWinUIApplication.Current.Services;
#elif ANDROID
    MauiApplication.Current.Services;
#elif IOS || MACCATALYST
    MauiUIApplicationDelegate.Current.Services;
#else
    null;
#endif }
like image 185
Tyson Swing Avatar answered Mar 29 '26 08:03

Tyson Swing


The solution of @Blush worked for me. I changed it a little bit. Instead of passing an action I just pass a collection of plattform specific services and add those too.

// android implementation
protected override MauiApp CreateMauiApp()
{
    IServiceCollection services = new ServiceCollection();
    services.AddSingleton<ITestService, TestService>();

    return MauiProgram.CreateMauiApp(services);
}

// shared app
public static MauiApp CreateMauiApp(IServiceCollection platformServices)
{
     var builder = MauiApp.CreateBuilder();

     // register shared services
     builder.Services.AddTransient<SharedService>();

     // register platform specific services
     foreach (var service in platformSpecificServices)
     {
         builder.Services.Add(service);
     }

     return builder.Build();
}
like image 34
nz-io Avatar answered Mar 29 '26 07:03

nz-io