Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Xamarin

Implement Dependency Injection in Xamarin using Autofac

3.22/5 (4 votes)
12 Nov 2018CPOL 10.7K  
How to organize the container

Introduction

I was working in a Xamarin.Form application that has a main application and services running at the same time. They share some features that need to be singleton. I needed to find a way to organize the container to be accessible by all of them.

Background

This link gives you an introduction about DI in Xamarin and Autofac. To have more details about how to install and get started with Autofac, you can check this link.

Using the Code

In order to organize the container in a single place, I created a new class DIContainer for the container. This class registers the services and exposes them as public properties.

C#
using Autofac;

public static class DIContainer 
{ 
   private static IContainer _container;

   public static IServiceA ServiceA { get { return _container.Resolve<IServiceA>(); } } 
   public static IServiceB ServiceB { get { return _container.Resolve<IServiceB>(); } } 

   public static void Initialize() 
   { 
     if (_container == null) 
     { 
        var builder = new ContainerBuilder(); 
        builder.RegisterType<ServiceA>().As<IServiceA>().SingleInstance(); 
        builder.RegisterType<ServiceB>().As<IServiceB>().SingleInstance(); 
        _container = builder.Build(); 
      }
    }
 }

To use a service, each application or service running must firstly initialize the container calling the method Initialize. After that, they can access the services through the public properties.

In my case, I add the following call in the App.xaml.cs of my application:

C#
DIContainer.Initialize();

Later, each page should use the public properties of the container to get the reference to the service needed and pass it to their view model if required.

C#
IServiceA service = DIContainer.ServiceA;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)