Last active
January 26, 2024 21:45
-
-
Save aritchie/a8e698d81369c1f819a4196301a8cd76 to your computer and use it in GitHub Desktop.
MAUI Service Locator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.Logging; | |
using System; | |
namespace YourNamespace; | |
// IMauiInitializeService will register immediately after MAUI has built its service container, so this class will be ready to go for all of your code | |
public class MyServiceLocator : Microsoft.Maui.Hosting.IMauiInitializeService | |
{ | |
public static IServiceProvider Services { get; private set; } | |
public void Initialize(IServiceProvider services) | |
{ | |
Services = services; | |
} | |
} | |
// In your MauiProgram.cs | |
services.AddSingleton<IMauiInitializeService, MyServiceLocator>(); | |
// In your code where dependency injection is hard to get at | |
var service = MyServiceLocator.Services.GetService(...); |
Forgot to add that. Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My case is not initialized MyServiceLocator => Exception : Services is null
Soultion
services.AddSingleton<IMauiInitializeService, MyServiceLocator>();
instead ofservices.AddSingleton<MyServiceLocator>();