In this article, we will learn the following
- Dependency service basics
- Create interface in PCL
- Implementation Per Platform
- 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.
- Capturing images
- Network connectivity checking
- Getting battery information
- Senor information
- 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.
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.
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:
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:
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.