DependencyService.Get<>() not working

Ayt*_*tee 2 dependency-injection xamarin xamarin.forms

I'm developing an app with xamarin.forms which hase to play some sound. For that is created an interface 'IAudioPlayer'

namespace ClassLibrary.AudioPlayer
{
    public interface IAudioPlayer
    {
        void PlayAudio(string filename);
    }
}
Run Code Online (Sandbox Code Playgroud)

And in the droid project i've got the implementation like this:

using System;
using Android.Media;
using Xamarin.Forms;

[assembly: Dependency(typeof(myApp.Droid.AudioPlayer_Android))]

namespace myApp.Droid
{
    public class AudioPlayer_Android : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ClassLibrary.AudioPlayer.IAudioPlayer, AudioTrack.IOnPlaybackPositionUpdateListener
    {
        public void PlayAudio(string filename)
        {
            var player = new MediaPlayer();
            var fd     = global::Android.App.Application.Context.Assets.OpenFd(filename);

            player.Prepared += (s, e) =>
            {
                player.Start();
            };

            player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
            player.Prepare();
        }

        public void OnMarkerReached(AudioTrack track)
        {
            throw new NotImplementedException();
        }

        public void OnPeriodicNotification(AudioTrack track)
        {
            throw new NotImplementedException();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

now when i call DependencyService.Get<ClassLibrary.AudioPlayer.IAudioPlayer>(); it breaks and says "Method 'Get' not found in type 'Xamarin.Forms.DependencyService'. When im Using DependencyService.Get<>() with another Type (Local DB implementation for example) it works fine.

Any Idea what i'm doing wrong here?

Kru*_*lur 5

您的实现IAudioPlayer是一个 Android Activity. 依赖服务将尝试创建它的一个实例 - 可能不是一个好主意。我无法真正解释您遇到的错误,但您应该创建一个仅使用一个接口的具体实现:

public class MyAndroidPlyer : IAudioPlayer
{}
Run Code Online (Sandbox Code Playgroud)

Forms 依赖服务只有非常基本的功能(你可以在这里查看源代码)

如果您需要更复杂的东西,还有其他选择,例如MvvmLight/SimpleIOC