#Xamarin.Forms Simple Dependency Injection (very simple #IoC)

2019-08-01 09_05_23-injection - Google SearchYou should use Dependency Injection as a design principle (aka IoC).  Here’s why. But you are here because you already want to and understand the need and benefits. Here’s how to in Xamarin Forms, simply.

First, go to NuGet and install Simple Injector into the main project of your solution. I’ve used this on projects with hundreds of thousands of uses and it works brilliantly in Xamarin.

We will need an Interface file and a class that implements that Interface:

    public interface IAnimal
    {
	    bool CanEatGrass();
    }
 
    public class DogIAnimal
    {
	    public bool CanEatGrass()
	    {
		    return false;
	    }
    }

Add a public static class to your App.xaml.cs so that you can access your IoC:

private static Container ioCContainer = new SimpleInjector.Container();
public static Container IoCContainer
{
	get => ioCContainer;
	set => ioCContainer = value;
}

Go to your App.xaml.cs file’s constructor and tell Simple Injector what kind of animal to get when an animal is requested:

App.IoCContainer.Register<IAnimalDog>(Lifestyle.Transient);


Now we are all wired up, let’s use it.

In your Pages.xaml.cs files’ constructors you usually create your model, in our case a Dog model. You can use the IoC to create it…and more importantly, any interfaces in the Dog’s constructor will be created too, so if you have dozens of tools like Loggers and Data layers, etc, they will all be created, and all of their dependencies and on and on. One line of code now:

BindingContext = App.IoCContainer.GetInstance<IAnimal>();

Done. Wasn’t that simple?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s