Chapter 4. Platform Specific Services and Dependency Injection

This chapter will not attempt to teach everything there is to know about Inversion of Control (IoC) and dependency injection, as there are numerous resources available that strictly focus on these topics alone. Instead, this chapter will focus on how these patterns apply to mobile development and, more specifically, how to implement them in a Xamarin.Forms mobile app.

Here is a quick look at what we'll cover in this chapter:

  • The need for dependency injection in multi-platform mobile app development
  • Implementing IoC and dependency injection using a third-party library in place of the Xamarin.Forms DependencyService
  • Creating, injecting, and using platform-specific services
  • Updating our TripLog app to use platform-specific services through IoC and dependency injection

Inversion of control and dependency injection in mobile apps

In software development, IoC and dependency injection solve many problems. In the world of mobile development, specifically multi-platform mobile development, they provide a great pattern to handle platform and device-specific code. One of the most important aspects to multi-platform mobile development is the idea of sharing code. Not only does development become easier and quicker when code can be shared across apps and platforms, but also maintenance, management, feature parity, and so on. However, there are always parts of an application's codebase that simply cannot be shared due to its strict tie in with the platform's APIs. In most cases, an app's user interface represents a large portion of this non-sharable code. It is because of this that the MVVM pattern makes so much sense in multi-platform mobile developmentā€”it forces the separation of user interface code (Views) into individual platform-specific libraries, making it easy to then compartmentalize the rest of the code (ViewModels and Models) into a single, sharable library.

But what if the code in the shared ViewModels needs to do something like access the device's physical geo-location, or leverage the device's camera to take a photo? Because the ViewModels exist in a single platform-agnostic library, they can't call the platform specific APIs. This is where dependency injection saves the day.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.216.75