
Creating the bootstrapper
The bootstrapper's responsibility is to initialize Autofac. It will be called at the startup of the application. We can create it as follows:
- In the root of the .NET Standard library project, create a new file called Bootstrapper.cs.
- Enter the following code:
using Autofac;
using System.Linq;
using Xamarin.Forms;
using DoToo.Views;
using DoToo.Repositories;
using DoToo.ViewModels;
namespace DoToo
{
public abstract class Bootstrapper
{
protected ContainerBuilder ContainerBuilder { get; private
set; }
public Bootstrapper()
{
Initialize();
FinishInitialization();
}
protected virtual void Initialize()
{
var currentAssembly = Assembly.GetExecutingAssembly();
ContainerBuilder = new ContainerBuilder();
foreach (var type in currentAssembly.DefinedTypes
.Where(e =>
e.IsSubclassOf(typeof(Page)) ||
e.IsSubclassOf(typeof(ViewModel))))
{
ContainerBuilder.RegisterType(type.AsType());
}
ContainerBuilder.RegisterType<TodoItemRepository>().SingleInstance();
}
private void FinishInitialization()
{
var container = ContainerBuilder.Build();
Resolver.Initialize(container);
}
}
}
The Bootstrapper will be inherited by each platform since this is where the execution of the app begins. This will also give us the option to add platform-specific configurations. To ensure that we inherit from the class, we define it as abstract.
The ContainerBuilder is a class defined in Autofac that takes care of creating the container for us after we are finished with the configuration. The building of the container happens in the FinishInitialization method defined at the end and is called by the constructor right after we call the virtual Initialize method. We can override the Initialize method to add custom registrations on each platform.
The Initialize method scans the assembly for any types that inherit from the Page or ViewModel and adds them to the container. It also adds the TodoItemRepository as a singleton to the container. This means that each time we ask for a TodoItemRepository, we will get the same instance. The default behavior for Autofac (this may vary between libraries) is that we get a new instance for each resolution.