Reputation: 610
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.
Upvotes: 10
Views: 6888
Reputation: 49
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();
}
Upvotes: 4
Reputation: 123
Why not to say
public static MauiApp CreateMauiApp(Action<MauiAppBuilder> registerPlatformSpecificServices)
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>();
registerPlatformSpecificServices?.Invoke(builder);
return builder.Build();
}
and when you run the application from the platform specific code, send there a configurator function like
public MainApplication(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(RegisterServices);
private static void RegisterServices(MauiAppBuilder builder)
{
builder.Services.AddScoped<ISmsProvider, SmsProvider>();
}
Upvotes: 1
Reputation: 231
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 }
Upvotes: 12