Xamarin.Forms: A tutorial about DependencyService

Xamarin.Forms is fantastic, you write your code once inside your PCL/.NetStandard project and it will run on many different platforms.However sometimes we need to access directly the native platform. To do so, we can use something called DependencyService.DependencyService allows us to use platform-specific functionality from shared code.To use the DependencyService we need:

  • An interface inside our shared code
  • An implementation for each platform
  • A registration

After the DependencyService is ready, then we can call it from our shared code.If we want to add a Sqlite database to our Xamarin.Forms project, because we cannot create it directly in our shared code, we need to use a DependencyService so in this tutorial we are going to see how to use the DependencyService to create and use a Sqlite database in our multi platform app.

TUTORIAL

First of all, let’s create an empty Xamarin.Forms project using a .NetStandard project. For a tutorial on how to create a Xamarin.Forms project, you can read this guide: http://www.xamarinexpert.it/2018/03/03/xamarin-forms-a-guide-for-beginners/

Empty Xamarin Project
Fig.1 Structure of an empty Xamarin.Forms Project

In the first image you can see the structure of a Xamarin.Forms project.As we said, the creation of a DependencyService consists of 3 steps.

First Step – The interface

Now the first step to do, is to create the Interface for our DependencyService.Let’s create and add an interface called ISql to our .NetStandard project:

public interface ISql
{
    SQLiteConnection GetConnection(string dbname = "database.db3");
    SQLiteAsyncConnection GetConnectionAsync(string dbname = "database.db3");
}

This interface exposes two methods:GetConnection: Get a connection for the Sqlite database.GetConnectionAsync: Get an async connection for the Sqlite database.Really easy. Don’t you think?

Second Step – The implementation

Inside this second step, we need to implement the interface in each platform. Let’s start with Android

Android

We need to create in Android a class the implements the ISql interface, let’s call this class SqlImplementation:

public class SqlImplementation : ISql
{
    public SQLiteConnection GetConnection(string dbname = "database.db3")
    {
        var sqliteFilename = dbname;
        string documentsPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        // Documents folder
        var path = Path.Combine(documentsPath, sqliteFilename);
        var conn = new SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.FullMutex);
        return conn;
    }

    public SQLiteAsyncConnection GetConnectionAsync(string dbname = "database.db3")
    {
        var sqliteFilename = dbname;
        string documentsPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
        var path = Path.Combine(documentsPath, sqliteFilename);
        return new SQLiteAsyncConnection(path);
    }
}

We have basically implemented the two methods of our ISql interface. These two methods return the native connection to an Android Sqlite database.

iOS

Now we need to create the same class inside the native  iOS project:

public class SqlImplementation : ISql
{
    public SQLiteConnection GetConnection(string dbname = "database.db3")
    {
        var sqliteFilename = dbname;
        string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder

        var path = Path.Combine(documentsPath, sqliteFilename);
        var conn = new SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.FullMutex);
        return conn;
    }

    public SQLiteAsyncConnection GetConnectionAsync(string dbname = "database.db3")
    {
        var sqliteFilename = dbname;
        string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
        var path = Path.Combine(documentsPath, sqliteFilename);
        return new SQLiteAsyncConnection(path);
    }
}

As you can see the code is basically the same but it’s IMPORTANT to add the implementation to each platform you need to use, otherwise you’ll get an error.

UWP

Now it’s time to implement the interface for UWP:

public class SqlImplementation : ISql
{
    public SQLiteConnection GetConnection(string dbname = "database.db3")
    {
        var sqliteFilename = dbname;
        var path = Path.Combine(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
        var conn = new SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.FullMutex);
        return conn;
    }

    public SQLiteAsyncConnection GetConnectionAsync(string dbname = "database.db3")
    {
        var sqliteFilename = dbname;
        var path = Path.Combine(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
        return new SQLiteAsyncConnection(path);
    }
}

and this concludes the second step.

Third Step – The registration

it’s extremely important to register the DependencyService otherwise it will not work.Don’t worry, this step is incredibly easy, the only thing you need to do is to add this line of code in each SqlImplementation class just before the namespace:

[assembly: Dependency(typeof(SqlImplementation))]

so for example the final code of your Android implementation will be:

[assembly: Dependency(typeof(SqlImplementation))]

namespace YOURNAMESPACE
{
    public class SqlImplementation : ISql
    {
        public SQLiteConnection GetConnection(string dbname = "database.db3")
        {
            var sqliteFilename = dbname;
            string documentsPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
            var path = Path.Combine(documentsPath, sqliteFilename);
            var conn = new SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.FullMutex);
            return conn;
        }

        public SQLiteAsyncConnection GetConnectionAsync(string dbname = "database.db3")
        {
            var sqliteFilename = dbname;
            string documentsPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
            var path = Path.Combine(documentsPath, sqliteFilename);
            return new SQLiteAsyncConnection(path);
        }
    }
}

REMEMBER to add the assembly line to EACH of your SqlImplementation classes.

HOW TO USE IT

Now the DependencyService is ready, we just need to call use it. If we want to get the SqLite connection we just need to use a single line of code inside our share code:

SQLiteConnection database = DependencyService.Get<ISQLite>().GetConnection();

Now you have your sql connection in you shared code so you can start to use your SqLite database.

Sqlite Plugin

It’s extremely easy to use the DependencyService to add a Sqlite database to your Xamarin.Forms app, but if you want an already made solution, you can use my Sqlite plugin so after you install it, you can directly use your database with a single line of code:

SQLiteConnection conn = MTSql.Current.GetConnection("yourdatabasename.db3");

It cannot be easier than that.You can find a tutorial on how to use the plugin here: http://www.xamarinexpert.it/2018/03/01/sqlite-made-easy/The official page is here: http://www.xamarinexpert.it/plugins/mt-sqlite/You can find the nuget package here: https://www.nuget.org/packages/MarcTron.Sqlite

More

You have doubts about the DependencyService or Sql? You want to know more? Ask me adding a comment below this article.