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.
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:
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.
IServiceA service = DIContainer.ServiceA;