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);
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.
The dependencies can now be used from within the Commands.
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.
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.