Best practices for using Xamarin Plugins

I’m sure by now you’re aware of the great amount of Plugins available for Xamarin. There’s plugins for almost everything, connectivity, localstorage, settings etc etc.

Generally these plugins are very easy to use, you can download from nuget and start using in a few single lines. Most of the documentation/blogs will show the single liners. Which sounds good to begin with but calling a dependency/API directly isn’t good as it tightly couples your business logic and makes unit testing very difficult.

Fortunately most of the plugins are interface based which means they support Inversion of Control, even if they don’t have interfaces you can supply your own interfaces.

Let’s take a look at an example using the Acr UserDialogs plugin.

You’ll notice that even examples call the API directly.

await UserDialogs.Instance.AlertAsync("Test alert", "Alert Title");

No, no, no, don’t do this. Highly coupled code will end you in bad places.

The correct way, well one of the correct ways, to implement a service like this is to use a IOC container and have the dependencies injected into your PageModels. Any good Mvvm Framework will support this. In this example I’m going to show you how to implement using FreshMvvm.

Below I add the UserDialogs Instance into the IOC container during my application startup.

It’s a single line: FreshIOC.Container.Register<IUserDialogs> (UserDialogs.Instance);

Screen Shot 2015-07-23 at 10.46.14 am

Because I’m using the Mvvm Framework to push between PageModels I can easily have the plugin dependency injected into the object. In the sample below I’m using my QuotePageModel that shows the dialog when a quote is being saved. NB* Those dependencies are injected into the Model automatically.

Screen Shot 2015-07-23 at 10.56.10 am

The dependencies can now be used from within the Commands.

Screen Shot 2015-07-23 at 10.59.22 am

Now that we’ve setup dependencies correctly we can easily unit test our PageModel methods. In the sample below I’m using the Moq framework to Mock out our dependancies and Verify the Update Quote method gets called.

Screen Shot 2015-07-24 at 10.34.39 am

It’s a very small change and it’s very easy to implement, the tradeoff of using Plugins in this manner is well worth the effort.

All this code is taken from a sample app that I’ve uploaded to github.




Leave a Reply