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.
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 }
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With