Luke Smith
Luke Smith

Reputation: 1320

Xamarin Dependency Injection fails - crash while trying to get platform specific implementation

I've got a Xamarin Forms interface that defines a Bluetooth controller. I'm following the usual technique when trying to create an Android specific implementation of this (I will also do an iOS one when I get this working).

I define my interface as follows :

namespace ArduinoRobotController.Models
{
    public interface BluetoothControllerInterface
    {
         List<string> GetPairedDevices();
..

Then I have my platform specific implementation like this :

[assembly: Xamarin.Forms.Dependency(typeof(BluetoothControllerInterface))]
namespace ArduinoRobotController.Droid.Implementations
{
    public class BluetoothController : BluetoothControllerInterface
    {
..

Then finally back in one of my view models, I have this code to get the platform specific instance I need :

BluetoothControllerInterface bt = Xamarin.Forms.DependencyService.Get<BluetoothControllerInterface>();

It builds and runs, but crashes on the line above. The error states :

System.MissingMethodException: Default constructor not found for type ArduinoRobotController.Models.BluetoothControllerInterface at SystemRuntimeType.CreateInstanceMono

.. etc.

I've tried lots of different ways around doing this, including calling to register the implementation in normal code rather than as [assembly etc. Any help on this really appreciated.

Upvotes: 0

Views: 315

Answers (1)

Jason
Jason

Reputation: 89204

your registration needs to point to the concrete class, not the interface

[assembly: Xamarin.Forms.Dependency(typeof(BluetoothController))]

Upvotes: 3

Related Questions