0

I am little confused about DependencyService compared to CustomRenderer.

Can we use DependencyService in place of CustomRenderer. Where can we use DependencyService?

Paul Kertscher
  • 9,416
  • 5
  • 32
  • 57
R15
  • 13,982
  • 14
  • 97
  • 173

1 Answers1

2

TL/DR: No, they have different use cases, although they both provide methods to access functions of your target system.

The concept of cutom renderers is directly coupled to user interface elements. Basically for every kind of Xamarin.Forms controls there is a custom renderer, which delegates the rendering of the controls to system UI framework. Usually it maps a Xamarin.Forms control to a native UI element.

A dependency (resolved via the dependency service) is more of a general concept of platform specific functions (acutally it's not limited to platform specific implementations). You define an interface abstracting the functionality, for which you will provide platform specific implementations. Platform specific classes that implement this interface and are exposed to DependencyService via DependencyAttribute can be resolved at runtime with DependencyService.Get<T>() (where T has to be your interface type). The objects retrieved from Get can be used without knowing which class exactly implements the interface. It's kind of a very basic dependency injection (well, not really, but sort of) and can be used for any functionality that needs a platform specific implementation, not only for UI concerns.

Paul Kertscher
  • 9,416
  • 5
  • 32
  • 57
  • Thank you for your answer. Can't we use `DependencyService` with UI's ? As you said we can use `DependencyService` with platform specific functions, could you please name a few. – R15 Feb 26 '19 at 12:44
  • The common example is Test-to-speech. Back in the days, you would have implemented a `LocationService` (for GPS) with `DependencyService`, sharing files would be another platform specific function, .... – Paul Kertscher Feb 26 '19 at 12:46
  • Well, I'd assume that you *could* implement some UI stuff that way, but I really don't know, if you'd get in the way of Xamarin.Forms somehow. Is there any reason that you'd like to use it over a custom renderer? – Paul Kertscher Feb 26 '19 at 12:47
  • I do not have any specific. But have a look on [this](https://stackoverflow.com/questions/53932894/how-to-change-picker-background-color-in-xamarin-mac-platform/53932929#53932929) answer. Can Dep Service help here in any way. – R15 Feb 26 '19 at 12:50
  • TBH: I don't know. This would require delving into the depths of macOS UI programming. – Paul Kertscher Feb 26 '19 at 12:52