DependencyService in Xamarin

DependencyService is a static class in the Xamarin.Forms namespace. Shared or Portable projects can access the platform-based tweaks that are done in any specific platform projects using DependencyService.
How it works?
The key point is by defining an interface.
DependencyService
The following are a few catches here,
Let's do it
Let's create a Xamarin.Forms Portable project with iOS, Android and Windows Phone. Name it DependencyDemo. Once the Solution is ready, add a new interface to the Portable project and name it asIDependencyDemo, add the following code to the interface.
  1. namespace DependencyDemo
  2. {
  3. public interface IDependencyDemo
  4. {
  5. string GetThePlatformMessage();
  6. }
  7. }
Interface
Build the Solution
Now let's implement the class in the platform-specific projects. Let's add new classes with the same name “DependencyImplementation” to each platform project and implement the interface in them.
Note: It is not required at all, for the class names to be the same. We have done it for our convention.
Android implementation
  1. [assembly: Xamarin.Forms.Dependency(typeof(DependencyDemo.Droid.DependencyImplementation))]
  2. namespace DependencyDemo.Droid
  3. {
  4. public class DependencyImplementation:IDependencyDemo
  5. {
  6. public string GetThePlatformMessage()
  7. {
  8. return "I am Android";
  9. }
  10. }
  11. }
iOS implementation
  1. [assembly: Xamarin.Forms.Dependency(typeof(DependencyDemo.iOS.DependencyImplementation))]
  2. namespace DependencyDemo.iOS
  3. {
  4. public class DependencyImplementation:IDependencyDemo
  5. {
  6. public string GetThePlatformMessage()
  7. {
  8. return "I am iOS";
  9. }
  10. }
  11. }
Windows Phone implementation
  1. [assembly: Xamarin.Forms.Dependency(typeof(DependencyDemo.WinPhone.DependencyImplementation))]
  2. namespace DependencyDemo.WinPhone
  3. {
  4. public class DependencyImplementation:IDependencyDemo
  5. {
  6. public string GetThePlatformMessage()
  7. {
  8. return "I am Android";
  9. }
  10. }
  11. }
Now let's test it by navigating back to the DemoDependency Portable project. Open the App.cs and place the following code in it.
  1. namespace DependencyDemo
  2. {
  3. public class App
  4. {
  5. public static Page GetMainPage()
  6. {
  7. string whoAmI = DependencyService.Get<IDependencyDemo>().GetThePlatformMessage();
  8. return new ContentPage
  9. {
  10. Content = new Label
  11. {
  12. Text = whoAmI,
  13. VerticalOptions = LayoutOptions.CenterAndExpand,
  14. HorizontalOptions = LayoutOptions.CenterAndExpand,
  15. },
  16. };
  17. }
  18. }
  19. }
Set the individual platform project as the Start Up Project and try to run the apps one after the other.
I hope this helps. Enjoy coding.