Forum Xamarin.Forms

Dependency Injection with Prism in Xamarin.Forms

Hello together,
i am trying to use the Prism Framework for a new Xamarin.Forms app, but am struggling with a special case of dependency injection. All i want to do is handle accelerometer-data in the forms code. So i implemented an interface in the PCL "IAccelerometer":

public interface IAccelerometer
{
    event EventHandler<AccelerometerResult> MeasurementReceived;
    void OnAccelerationChanged(AccelerometerResult result);
}

In the android app, i implemented "AccelerometerDroid":

[assembly: Dependency(typeof(AccelerometerDroid))]
namespace PrismTestApp.Droid.Services.Accelerometer
{
    public class AccelerometerDroid : IAccelerometer
    {
    }
}

Then in my viewmodel, i get the interface via the constructor:

public class ViewAViewModel : ViewModelBase
{
    IAccelerometer _accelerometer;
    public ViewAViewModel(INavigationService navigationService, IAccelerometer accelerometer)
        : base (navigationService)
    {
    }
}

So far, so good, i get my accelerometer-instance and everything is fine. But now i need to get the android sensor in my android implementation. As far as i know, i would have to get the sensor in my andoird MainActivity.OnCreate:

var sensorManager = (SensorManager)GetSystemService(Context.SensorService);
var sensor = sensorManager.GetDefaultSensor(SensorType.Accelerometer);
sensorManager.RegisterListener(sensorListener, sensor, SensorDelay.Ui);

If i would want to do that in my AccelerometerDroid-class, i dont have all that Context stuff, as well as the GetSystemService-method. So my question is, how can i connect those both? At runtime of the OnCreate-method, my Accelerometer isn't instantiated already, so that i would be able to pass it from the activity to the AccelerometerDroid.

I would be very glad if someone could help me here, thanks in advance!

Sign In or Register to comment.