Dependency injection in Xamarin.Forms

I am using Xamarin.Forms to develop a multiplatform application. One of the challenges I faced when developing, is that I needed an abstract way to get the display dimensions for Xamarin.iOS and Xamarin.Android (as Xamarin.Forms doesn’t provide a way to do it). The challenge was that I needed to target both platforms in the Xamarin.Forms project. With some help from this post I managed to come up with a solution. The first part that you should do is create a new interface called IDisplay.cs in your shared project.

Screen Shot 2014-09-17 at 12.04.34

After you created the interface, put the following code into the file:

Now we need an implementation for both iOS and Android. To do this, create a class called Display.cs in both projects. I just put the Display class in the root project. You probably want to put it in a package or something, but that is up to you.

Screen Shot 2014-09-17 at 09.08.45

And this is the Android implementation of the Display.cs class:

 

The goal is to use this class when the Xamarin.Forms project is started for Android. To achieve this we add this line to the AssemblyInfo.cs class in the Properties folder (you can add it to the bottom of the file):

Now in our Xamarin.Forms project, we can get the platform specific class at runtime in the following way:

Now you can get the right class depending on what platform you made the Display.cs class for.

If you have any questions, feel free to ask in the comments!