Search code examples
xamarinxamarin.formsdependency-resolver

Xamarin.Forms DependencyService not for all platforms


In the docs it is clearly stated that you need an implementation for all platforms:

You must provide an implementation in every platform project. If no Interface implementation is registered, then the DependencyService will be unable to resolve the Get<T>() method at runtime.

I haven't provided an implementation and so the app crashed. But what should I do in the case, that I don't need an implementation for that platform? Providing a bodyless method like this?

public void HideKeyboard()
{
    // We need an implementation for the DependencyService, even it is empty.
}

Should I provide an implementation nevertheless?

public void HideKeyboard()
{
    try
    {
        InputPane myInputPane = InputPane.GetForCurrentView();
        myInputPane.TryHide();
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
}

Or is the use of DependencyService the wrong option here?


Solution

  • I am assuming that you do not need an implementation on one platform, but do on the other.

    There is basically two things you can do:

    • Provide a bodyless implementation on the platform where you don't need an actual implementation, like you suggested yourself
    • or; put a check for the platform around the DependencyService call.

    If you need it only on iOS, just do it like this in your shared code:

    if (Device.RuntimePlatform == Device.iOS)
        DependencyService.Get<IKeyboardService>().HideKeyboard();
    

    This way you don't litter your code with a redundant class. You do need to add this in all places where you're going to execute this code. So what the better option is here is up to you.

    Using the DependencyService isn't wrong and actually the only way to reach this kind of platform specific functionality.