Skip to content
Home » Code Snippet: Service Provider

Code Snippet: Service Provider

Dependency Injection makes life easier also in .NET MAUI. From time to time it is necessary to reference a service that does not come via the constructor. Here is a simple solution for this:

public static class ServiceProvider
{
    public static TService GetService<TService>()
        => Current.GetService<TService>();

    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
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *