官术网_书友最值得收藏!

  • Xamarin Blueprints
  • Michael Williams
  • 323字
  • 2021-07-08 11:48:23

Inversion of Control (IoC) with Xamarin.Forms

The Inversion of Control (IoC) principle is very a useful technique when writing cross-platform applications.

So why should we use it?

Sharing 100% of the code would be great, but it is not entirely possible; we still require some implementation from platform-specific features (for example different platform services, hardware, cameras). A way to tackle this problem is via an IoC container. Using the IoC principle, we use an abstraction for the functionality in our shared code and pass an implementation of the abstraction into our shared code. Our IoC containers handle the instantiation of an object's dependency tree. We can register objects to their inherited interfaces and allow containers to pass registered objects as their abstracted interfaces all the way down the dependency tree (all the way to PCL).

So how do we benefit from this?

What if I needed view models to call methods to a native Bluetooth service in a PCL project?

To put it simply, we can't. Our PCL projects know nothing about Bluetooth services on the native side. We create an interface that sits in the PCL project, create a class that inherits this interface, and define the methods and access all the native features required. We then register this class to the inherited interface through our IoC container, and finally resolve this abstracted interface in our PCL project. When we call functions from this interface down in the PCL, it will be calling the registered class function definitions described on the native side:

Now back to our SpeechTalk application. Because the PCL project cannot share code from the native side text-to-speech services, we will have to use IoC to access the native-side features from our PCL. Let's start by declaring an interface for our text to speech service, creating a new folder called Services, and adding a new ITextToSpeech.cs file for the interface:

public interface ITextToSpeech 
    { 
        void Speak (string msg) 
    } 
主站蜘蛛池模板: 乌拉特前旗| 南充市| 桦南县| 商城县| 奎屯市| 安化县| 晋州市| 扶绥县| 贵南县| 富蕴县| 东兰县| 青铜峡市| 钟祥市| 建阳市| 大连市| 华池县| 东平县| 象山县| 安溪县| 滕州市| 安达市| 文昌市| 汝州市| 汉源县| 凌海市| 洪江市| 南澳县| 东丽区| 石屏县| 井冈山市| 洮南市| 丰城市| 许昌县| 五台县| 长葛市| 安乡县| 彰武县| 沐川县| 家居| 塔河县| 建昌县|