Click here to Skip to main content
15,884,917 members
Articles / Mobile Apps / Xamarin
Tip/Trick

Implement Dependency Injection in Xamarin using Autofac

Rate me:
Please Sign up or sign in to vote.
3.22/5 (4 votes)
12 Nov 2018CPOL 10.4K   2   2
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)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionInjection e HttpClienteFactory Pin
alessandrodk10-Aug-21 3:50
alessandrodk10-Aug-21 3:50 
QuestionConstructor injection and pages classes (MainPage, etc.) Pin
Member 115869146-Dec-19 10:00
Member 115869146-Dec-19 10:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.