Monday, December 27, 2021

Using Platform Specific Code Inside Xamarin.Forms

First declare an interface in the main project. Something like the following: 

namespace myapp
{
    public interface ILoginService
    {
        void DoLogin(); 
    }
}

Implement the interface in a concrete class inside the android project. 

[assembly: Dependency(typeof(myapp.Droid.AndroidLoginService))]
namespace myapp.Droid
{
    
    class AndroidLoginService : myapp.ILoginService
    {
        public void DoLogin()
        {
            /* implement here */
        }
    }
}

Notice the Dependency attribute. This registers the class with the dependency injection engine in Xamarin. Now you can use the implementation in the main project. 

var loginsvc = DependencyService.Get<ILoginService>();
loginsvc.DoLogin();

Hopefully that helps you use platform specific implementations inside Xamarin.Forms.