Xamarin.Forms: DependencyService
Tuesday, September 26, 2017

Last month I made a blogpost/tutorial where I used DependencyService and I got some email question related to that, so I decided to make a blog post about DepdendencyService.
Before you read this blog post I want to show you a great resource from Xamarin developer docs at this url:
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/introduction/
That is a great explanation of usage of Depdendency Service in Xamarin.Forms apps.
For this blog post I will create new empty app, and inside of it I will create one folder called Helpers with interface: IDbPath.
We will not use real local database implementation for this blog post because db is not important for us at this moment, this blog post has a purpose to explain simple usage of DependencyService.
DependencyService allows apps to call into platform-specific functionality from shared code in our case our PCL or .NET Standard Library. With this functionality Xamarin.Forms apps can do anything that a native app can do, in this case we need to get default db path from our platforms, because we use PCL we can not directly access to that path value, so we need some mechanism to get that values from platforms specific projects.
Before we start with DependencyService I strongly recommend you to take a look at this great image from Xamarin docs:

Image Source:
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/introduction/
To be honest when I first saw this image I did not know what was happening, to understand this I needed to implement some functionality with this, and best example in my opinion is sqlite path that you need to get in your shared code (PCL or .NET Standard library) from platform specific projects.
Three main components of DependencyServices are:
- Our interface
- Platform specific implementation
- Shared code implementation
Interface:
So to start with our tutorial in the Helpers folder create new interface called IDbPath and it should look like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace XF.DependencyService.Demo.Helpers { | |
public interface IDbPath { | |
string GetPlatformDBPath(); | |
} | |
} |
Platform specific implementation:
To implement DependencyServices we need to make a classes in every platform specific project which implements our interface in this case our IDbPath interface.Create new class inside of Android project called DatabasePath.cs I will store it in folder Helpers, you can do it also like that if you want.
My class will look like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using Android.App; | |
using Android.Content; | |
using Android.OS; | |
using Android.Runtime; | |
using Android.Views; | |
using Android.Widget; | |
using XF.DependencyServices.Demo.Droid.Helpers; | |
using XF.DependencyServices.Demo.Helpers; | |
using System.IO; | |
[assembly: Xamarin.Forms.Dependency(typeof(DatabasePath))] | |
namespace XF.DependencyServices.Demo.Droid.Helpers { | |
public class DatabasePath : IDbPath { | |
// we must have a default (parameterless) constructor | |
public DatabasePath() { } | |
public string GetPlatformDBPath() { | |
// Android OS Platform Specific code | |
return Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "LocalDB.db"); | |
} | |
} | |
} |
As you can see we have couple of main parts, first one is DependencyService registration with a metadata attribute above namespace of the class, second one is implementing the IDbPath interface with method GetPlatformDBPath(), inside this method is one line of code for returning the database path and we need to have empty constructor.
Other implementations for ios and uwp looks like this:
iOS:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using Foundation; | |
using UIKit; | |
using XF.DependencyService.Demo.iOS.Helpers; | |
using XF.DependencyServices.Demo.Helpers; | |
using System.IO; | |
[assembly: Xamarin.Forms.Dependency(typeof(DatabasePath))] | |
namespace XF.DependencyService.Demo.iOS.Helpers { | |
public class DatabasePath : IDbPath { | |
// we must have a default (parameterless) constructor | |
public DatabasePath() {} | |
// iOS Platform Specific code | |
public string GetPlatformDBPath() { | |
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", "LocalDB.db"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Windows.Storage; | |
using XF.DependencyService.Demo.UWP.Helpers; | |
using XF.DependencyServices.Demo.Helpers; | |
[assembly: Xamarin.Forms.Dependency(typeof(DatabasePath))] | |
namespace XF.DependencyService.Demo.UWP.Helpers { | |
public class DatabasePath : IDbPath { | |
// we must have a default (parameterless) constructor | |
public DatabasePath() { } | |
// UWP Platform Specific code | |
public string GetPlatformDBPath() { | |
return Path.Combine(ApplicationData.Current.LocalFolder.Path, "LocalDB.db"); | |
} | |
} | |
} |
Shared code implementation:
Now we can use this methods in our shared project to retrieve those values from platform specific projects.For easier demonstration first thing that I will make is a button in our MainPage.xaml, and it will have one event when this button is Clicked.
Xaml looks like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" | |
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" | |
xmlns:local="clr-namespace:XF.DependencyServices.Demo" | |
x:Class="XF.DependencyServices.Demo.MainPage"> | |
<Button HorizontalOptions="Center" | |
VerticalOptions="Center" | |
Text="Show database path" | |
Margin="32" | |
Clicked="ShowDatabsePath" /> | |
</ContentPage> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Xamarin.Forms; | |
using XF.DependencyServices.Demo.Helpers; | |
namespace XF.DependencyServices.Demo { | |
public partial class MainPage : ContentPage { | |
public MainPage() { | |
InitializeComponent(); | |
} | |
private void ShowDatabsePath(object sender, EventArgs e) { | |
// Usage of DependencyService | |
var dbPath = DependencyService.Get<IDbPath>().GetPlatformDBPath(); | |
// Displaying the result from GetPlatformDBPath() | |
DisplayAlert("Db Path:", dbPath, "Ok"); | |
} | |
} | |
} |
In the next line we are displaying that value in DispalyAlert and that is it, of course in real usage of sqlite we will not display this path we will use it to make our db, but that is not the topic of this tutorial.
Here is a app running on android and uwp, I am not testing the iOS but it works I promise 😂.

And that is it, implementation is really simple as you can see from this blog post, If there is something blurry you can ask in the comment section below.
Some conclusion words: As you can see from this blog post DependencyService is very powerful feature in Xamarin.Forms, DependencyServices allows us to get some platform specific values in our PCL/.NET Standard library shared code project and use it later if you need it.
Source code you can find on my GitHub page here:
https://github.com/almirvuk/XF.DependencyService.Demo/
I hope that this blog post/tutorial was helpful for you.
Best regards!
5 comments
any chance to fix your code snippets to be printable without being cut off? Thanks
ReplyDeleteHi,
DeleteWhat do you mean by that?
Best regards!
This comment has been removed by a blog administrator.
ReplyDeleteMan, love what you are doing! Very helpful and powerful blog. Thanks a lot for super job. Xamarin + EFCore + MVMV + DependencyService just rocks!
ReplyDeleteThank you very much! Nice to hear that!
Delete