How do you resolve services from a static or platform context where constructor injection isn't possible?
Short answer
Expose the app's IServiceProvider. A common approach is a static helper that reads IPlatformApplication.Current.Services, used sparingly at boundaries (e.g., inside a platform callback). Keep such access at the edge and pass resolved services into normal injected code.
Advertisement
AModel answer
Expose the app's IServiceProvider. A common approach is a static helper that reads IPlatformApplication.Current.Services, used sparingly at boundaries (e.g., inside a platform callback). Keep such access at the edge and pass resolved services into normal injected code.
public static class ServiceHelper
{
public static T Get<T>() where T : notnull =>
IPlatformApplication.Current!.Services.GetRequiredService<T>();
}Real-world example
A push-notification native callback, which can't use constructor injection, uses ServiceHelper.Get to obtain the message handler and then delegates to injected logic.
Likely follow-ups
- Why keep this at the boundary? | What is IPlatformApplication?
Related topics