Platform specific code with Xamarin and Prism

When writing platform specific code within our iOS, Android and UWP projects we can use the built-in lightweight dependency injection code and attributes that comes out of the box with Xamarin, but when using Prism we’re probably using Unity or DryIoc as our preferred IoC library.

Let’s look at a simple example, whereby I have an interface in my shared code, which looks like this

public interface IFileService
{
   void Save(string data);
}

although there is file handling code etc. in .NET standard and we can implement something like this in the shared code, maybe we want some other more specific platform code. Here’s an Android file (i.e. within the Android project)

[assembly: Dependency(typeof(FileService))]
namespace Droid.Services
{
    public class FileService : IFileService
    {
        public void Save(string data)
        {
            // some Android specific code
        }
    }
}

The use of the DependencyAttribute makes this class available via Xamarin Forms built-in DependencyService, but not available to DryIoc, for example – hence what we want to do is use the built-in DI container and map this to our preferred IoC library.

All we need to do in our shared project’s App.xaml.cs file within the RegisterTypes method, we just do something like this

containerRegistry.RegisterInstance(DependencyService.Get<IFileService>());

Simple.