Skip to content

Instantly share code, notes, and snippets.

@aritchie
Last active January 26, 2024 21:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aritchie/a8e698d81369c1f819a4196301a8cd76 to your computer and use it in GitHub Desktop.
Save aritchie/a8e698d81369c1f819a4196301a8cd76 to your computer and use it in GitHub Desktop.
MAUI Service Locator
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(...);
@JaehwanMango
Copy link

JaehwanMango commented Oct 24, 2022

My case is not initialized MyServiceLocator => Exception : Services is null

Soultion
services.AddSingleton<IMauiInitializeService, MyServiceLocator>(); instead of services.AddSingleton<MyServiceLocator>();

@aritchie
Copy link
Author

Forgot to add that. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment