HomeAbout Me

Quick Tip - Accessing The Service Provider in .NET MAUI

By Michael Stonis
Published in Development
July 05, 2024
Quick Tip - Accessing The Service Provider in .NET MAUI

Better Service Resolution in .NET 8

In .NET MAUI we have very good access to dependency injection and primary constructors which makes things like the following very easy.

public class MyClass(IProvideCoolThings myservice)
{
...
}

However, there are cases when you cannot use the constructor to resolve dependencies or need to resolve a dependency in a lazy manner at runtime. This is most common when you are in the context of a .NET MAUI view. In .NET 7 and earlier, the best way to do this was to use the view’s Handler and MauiContext to get the service provider.

myVisualElement.Handler.MauiContext.Services.GetServices<IService>();

This works well when resolving a service late or via lazy loading, but it has some issues. For example, if the Handler has not been assigned yet to the view, you will end up with a null reference exception. Additionally, if you are outside of a view, say in an extension method, getting access to the service provider was problematic as there was no direct way to get access to it unless you built a wrapper to get access to the service provider like in this example.

Fortunately, with .NET MAUI 8, we no longer need any kind of workaround and can access services anywhere in our app using IPlatformApplication.Current. IPlatformApplication.Current has a Services property which is a reference to the service provider. IPlatformApplication.Current is also available immediately on app start, so it is safe to reference within your custom pages or controls without delay.


Tags

#dotnet#dotnet_maui#maui

Share

Previous Article
Getting the Android Emulator Working with Visual Studio for Mac on an M1 Machine

Quick Links

Eight-BotAbout Me

Social Media