Xamarin.Forms.DependencyService platform tweaks

What is DependencyService in Xamarin ?

DependencyService is a static class under Xamarin.Forms namespace. Shared or Portable projects can access the platform based tweaks that are done in any specific platform projects by using DependencyService.

How it works?

The key point is by defining an Interface.

  • Declare an Interface in the Shared / Portable project.
  • Implement the interface in platform specific projects.
  • Register the class under DependencyService Assembly with Dependency attribute.
  • Call the DependencyService.get method with the Interface. It will identify the platform and executes the implementation

Xamarin.Form.DependencyService

 

Few catches here :

  • The class which implements the Interface must have a parameter less constructor defined.
  • [assembly: ] attribute must be declared above the namespace. I have seen often developers doing this mistake.
  • Implementation has to be done in each platform specific projects that are present in the Solution.  It has a valid reason as well, since we are implementing in a shared repository, it is obvious that we will use the same code base for all of the platforms. In that case, the platform don’t have the implementation will through a NullReferenceException.

Let’s do it

Let’s create a Xamarin.Forms Portable project with iOS, Android and Windows Phone. Name it as DependencyDemo. Once the Solution is ready, add a new Interface to the Portable project and name it as IDependencyDemo, Add the following code to the interface.

Interface

Build the Solution.

Now let’s implement the class in the platform specific projects. Let’s add new classes with same name “DependencyImplementation” to each platform projects and implement the interface in them.

NOTE: It is not required at all, for the class names to be same. We have done it for our convention.

Android implementation

iOS implementation

Win Phone implementation

Now let’s test it by navigating back to the DemoDependency Portable project Open the App.cs and place the below code in it.

Set the individual platform project start up project and try to run the app one after the other.

 

Hope this helps.  Enjoy coding 🙂

Categories: Android, Cross Platform Mobile App, iOS, Windows Phone, Xamarin

Leave a Reply

%d bloggers like this: