[Xamarin][筆記]簡介DependencyService

  • 1710
  • 0

DependencyService的目的是讓shared code可以依不同的手機平台呼叫該平台的特定功能。它的運作方式是會先在shared code 定義interfaceDependencyService則依據不同的平台專案解析及取得各平台的實作。

 

建立DependencyService

要建立一個DependencyService有以下幾個步驟﹔

1.建立Interface

例如建立一個文字轉語音功能的DependencyService,會在Share Code建立一個如下的Interface

public interface ITextToSpeech {
    void Speak ( string text ); 
}

2.在各手機平台的專案中實作該Inferface

一旦Interface定義好之後,接下來需要在各手機平台的專案中實作該Inferface,以下的例子是在Windows Phone中實作。

namespace TextToSpeech.WinPhone
{
  public class TextToSpeechImplementation : ITextToSpeech
  {
      public TextToSpeechImplementation() {}

      public async void Speak(string text)
      {
          SpeechSynthesizer synth = new SpeechSynthesizer();
          await synth.SpeakTextAsync(text);
      }
  }
}

要注意到的是,一定要建立default constructor,以讓DependencyService使用。

3.設定Attribute以進行Register

Register可讓DependencyService 找到實作Interface的實作function。如以下的程式碼,

using TextToSpeech.WinPhone;

[assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechImplementation))]
namespace TextToSpeech.WinPhone {
  ...

使用DependenceService

當各平台的專案都已經實作好Interface之後,就可以在Share Code中使用DependencyService.Get<T>以取得interface T在各手機平台的實作處理。

DependencyService.Get<ITextToSpeech>().Speak("Hello from Xamarin Forms");