Published on

Configuring MAUI to use Autofac as dependency injection framework

Reading time
4 min read

Why would you want to do that?

One reason would be that you want to migrate to MAUI while continue to use your existing dependency injection framework. Or just because frameworks like Autofac makes you feel comfort using them.

Many reasons and motivation to switch to a different dependency injection other than what's provided to you out of the box. In this post, I will give a quick guide on how to use and configure Autofac in MAUI application.

About the sample code

Sample code provided here is based on one of MAUI code samples. The sample in use here is ToDoSQLite sample in MAUI samples repository.

Configuring MAUI to use Autofac

Examining the existing MauiProgram.CreateMauiApp method. A common way of registering services would be like this

public static MauiApp CreateMauiApp()
{
	var builder = MauiApp.CreateBuilder();
	//... code omitted for clarity

    builder.Services.AddSingleton<TodoListPage>();
	builder.Services.AddTransient<TodoItemPage>();
	builder.Services.AddSingleton<TodoItemDatabase>();

	return builder.Build();
}

To configure MAUI to use Autofac you'll need to use ConfigureContainer method of the MauiAppBuilder class

public static MauiApp CreateMauiApp()
{
	var builder = MauiApp.CreateBuilder();
	//... code omitted for clarity

	builder.ConfigureContainer(new AutofacServiceProviderFactory(),
        autofacBuilder =>
        {
            autofacBuilder.RegisterType<TodoItemDatabase>().SingleInstance();
            autofacBuilder.RegisterType<TodoListPage>().SingleInstance();
            autofacBuilder.RegisterType<TodoItemPage>().InstancePerDependency();
        });
	return builder.Build();
}

The autofacBuilder parameter above is an instance of Autofac.ContainerBuilder class.

If you are using Autofac Modules. You can register your modules like this:

public static MauiApp CreateMauiApp()
{
	var builder = MauiApp.CreateBuilder();
	//... code omitted for clarity

	builder.ConfigureContainer(new AutofacServiceProviderFactory(),
                            autofacBuilder =>autofacBuilder.RegisterAssemblyModules(typeof(MauiProgram).Assembly));
	return builder.Build();
}

In my app assembly, I have 2 Modules defined:

internal class DataModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<TodoItemDatabase>().SingleInstance();
    }
}

internal class ViewsModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<TodoListPage>().SingleInstance();
        builder.RegisterType<TodoItemPage>().InstancePerDependency();
    }
}

Check full sample code here.