Dependency Service with Event Handlers

In this below article, we have learnt the basics of the dependency service

In this article, we are going to learn the following

  • How to create an interface with event handler
  • Implementing the Dependency service in Droid
  • Calling the Dependency Service

How to create an interface with event handler

First we need to create an interface with definitions of methods and event handler.For example, create an interface PositionChange which having the definition of one method Start() & positionChanged

    public interface PositionChange
                    void start ();
                    event EventHandler positionChanged;

In the PositionChange class code positionChanged is an event which passed PositionEventArgs object, for that we need to create a model class with name “PositionEventArgs

public class PositionEventArgs
               string position {get; set;}
               public PositionEventArgs (string pos)
                    position = pos;

Implementing the Dependency service in Droid

Once a suitable interface has been designed, PositionChange interface must be implemented in the project for each platform that you are targeting. For example, the following class implement the PositionChange interface on Android Phone

As in the previous article, we need to declare paramterless constructor.

[assembly: Xamarin.Forms.Dependency(typeof(CurrentLocationService_Android))]

namespace AndroidToPcl.Droid.Dependencies
public class CurrentLocationService_Android: PositionChange
           public static CurrentLocationService_Android () {}
           public event EventHandler positionChanged;
           public void start ()
                         myself = this;
                         var context = Xamarin.Forms.Forms.Context;
                         Intent intent= new Intent(context, typeof(ChangeActivity));
           public void receivedNewPosition (CustomPosition pos)
                        positionChanged (this,new positionEventArgs(pos.update));

Note: that the registration is performed at the namespace level, not the class level. In the above code, context is changing from Xamarin.Forms to Android.
Below code is representing the changing of context by calling native activity. We can navigate from one activity to another activity we need to use Intent.

Intent intent = new Intent(context, typeof(ChangeActivity));

In the ChangeActivity activity code, I have changed the position manually which will trigger an event in the page

[Activity(Label = “ChangeActivity”)]

public class ChangeActivity: Activity
      protected override void OnCreate (Bundle savedInstanceState)
            CustomPosition pos = new CustomPosition();
            pos.update = “Finally value is updated”;

Call to Dependency Service

Once the project has been set up with a common interface and implementations for each platform, use Dependency Service to get the right implementation at runtime. Below code represents how to call the dependency service in the page

private void BtnClick_Clicked(object sender, EventArgs e)
 currentLocationService = DependencyService.Get();
 currentLocationService.positionChanged += OnPositionChange;

Below code is use get the control when the position changed event is trigger

 private void OnPositionChange (object sender, PositionEventArgs e)
      Debug.WriteLine(“Got the update in ContentPage from service “);
      // code to do

Finally, we will get the updated string in the PositionEventArgs object e.  By this way we can get the data from the dependency service. We can achieve this with Message Center also.

That’s it; hope you have enjoyed reading this article


In this article, we have learnt the following

  • How to create an interface with event handler
  • Pass the data from native to forms using event handler.

Dependency Service in Xamarin

In this article, we will learn the following

  • Dependency service basics
  • Create interface in PCL
  • Implementation Per Platform
  • Registration
  • Call to Dependency Service.

Xamarin.Forms is a cross-platform UI toolkit that allows developers to easily create native user interface layouts that can be shared across Android, iOS, and Windows Phone. For achieving native features either we need to use third-party plugins or Dependency Service

Dependency Service allows us to access native functionalities. Few of them are listed below.

  1. Capturing images
  2. Network connectivity checking
  3. Getting battery information
  4. Senor information
  5. Hardware information

This functionality enables Xamarin.Forms apps to do anything that a native app can do.

The steps of the implementation of the Dependency service below


Create interface in PCL:

   We need to create an interface with the definition of the methods which interacts with platform specific functionalities. If you are developing a component to be shared as a component or Nuget package, API design can make or break a package.

Below example show how to find network connectivity.

Public interface IConnectivty

       bool IsConnectivityAvailable ();
      //note that interface members are public by default

Implementation per Platform:

After creating interface, we need to implement IConnectivty in each platform that we are targeting in the app. For example, the below ConnectivityImplementation class implementing the IConnectivty interface in Droid.

namespace CheckConnectivity.Droid
     public class ConnectivityImplementation: IConnectivty
           public ConnectivityImplementation () {}
           public async bool IsConnectivityAvailable ()
                           //code to get the connectivity
Context context =Xamarin.Forms.Forms.Context;

                           ConnectivityManager connectivityManager = (ConnectivityManager)context                        .GetSystemService(Context.ConnectivityService);
                           NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
                           if (activeConnection != null)
                                     bool isOnline = activeConnection.IsConnected;
                           return activeConnection != null && activeConnection.IsConnected;

Note that every implementation must have a default (parameterless) constructor for Dependency Service to be able to instantiate it. Parameterless constructors cannot be defined by the interface.


Each implementing class must be registered with Dependency Service via a metadata attribute. Registration enables Dependency Service to find the implementing class and supply it in place of the interface at run time. The following code registers the implementation for android phone:

using CheckConnectivity.Droid;

    [assembly: Xamarin.Forms.Dependency (typeof (ConnectivityImplementation))]
     namespace CheckConnectivity.Droid {
       //  ConnectivityImplementation class code

Call to Dependency Service:

Once the project has been set up with a common interface and implementations for each platform, use Dependency Service to get the right implementation at runtime:

DependencyService.Get ().Speak ();

Note that DependencyService.Get will find the correct implementation of interface T. we must provide an implementation in every platform project. If no Interface implementation is registered, then the Dependency Service will be unable to resolve the Get () method at runtime.

That’s it; hope you have enjoyed reading this article.  Get complete details with runnable code in next article


In this article, we have learnt the following

  • What is dependency service
  • How to create interface in PCL
  • Implementing, registration & calling of the dependency service in targeted platforms.