How do you register and consume platform-specific implementations of a shared interface?
Short answer
Define the interface in shared code, implement it per platform using partial classes or the Platforms folder, and register it in DI.
Advertisement
AModel answer
Define the interface in shared code, implement it per platform using partial classes or the Platforms folder, and register it in DI. A common pattern is a partial class with a shared signature and platform-specific bodies compiled per target, or conditional registration in MauiProgram.
// Shared
public interface IDeviceInfoService { string GetId(); }
// Platforms/Android/DeviceInfoService.cs
partial class DeviceInfoService : IDeviceInfoService
{
public string GetId() => Android.OS.Build.Serial ?? "unknown";
}
// MauiProgram.cs
builder.Services.AddSingleton<IDeviceInfoService, DeviceInfoService>();Real-world example
A team reads a hardware identifier differently on each OS but injects a single IDeviceInfoService everywhere in shared code.
Likely follow-ups
- How do partial classes multi-target? | Could you use conditional DI registration instead?
Related topics