2020.09.01.

Xamarin.Forms Portable DependencyService – platform specific implements

By bence960206

We do not always make the business logic involves the Portable project. Then you have to explain to each platform. This can be done if some kind of service to call and tell him that this is not the realization were discussed here, but each platform separately. Be the project name: DependencyServiceDemo.

How can we do this?

Very simply. We have to create an interface in the portable project.

public interface ISaveAndLoad

{

string LoadText(string text);

}

If you want to use the methods, we have two task yet:

  1. We have to call the DependencyServicet in the portable project.
  2. You should implements these methods for each platform.

Let’s start with the first one. Call the function via DependencyService:

string text = DependencyService.Get<ISaveAndLoad>().LoadText(”We call from the portable project, but ”);

Now we implement this function all three platforms:

UWP:

We have to create a class(SaveAndLoad.cs) and deriving this from this: ISaveAndLoad:

//this assembly’s addendum should be added

//using Xamarin.Forms; because we are using Dependency

//A typeof(SaveAndLoad) points on this class

//ISaveAndLoad points on the portable’s interface

[assembly: Dependency(typeof(SaveAndLoad))]

namespace DependencyServiceProba.UWP

{

public class SaveAndLoad : ISaveAndLoad

{

public string LoadText(string text)

{

return text + ”I’m UWP.”;

}

}

}

iOS:

We have to create a class(SaveAndLoad.cs) and deriving this from this: ISaveAndLoad:

//this assembly’s addendum should be added

//using Xamarin.Forms; because we are using Dependency

//A typeof(SaveAndLoad) points on this class

//ISaveAndLoad points on the portable’s interface

[assembly: Dependency(typeof(SaveAndLoad))]

namespace DependencyServiceProba.iOS

{

public class SaveAndLoad : ISaveAndLoad

{

public string LoadText(string text)

{

return text + “I’m iOS.”;

}

}

}

Android:

We have to create a class(SaveAndLoad.cs) and deriving this from this: ISaveAndLoad:

//this assembly’s addendum should be added

//using Xamarin.Forms; because we are using Dependency

//A typeof(SaveAndLoad) points on this class

//ISaveAndLoad points on the portable’s interface

[assembly: Dependency(typeof(SaveAndLoad))]

namespace DependencyServiceProba.Droid

{

public class SaveAndLoad:ISaveAndLoad

{

public string LoadText(string text)

{

return text + ”I’m Android.”;

}

}

}