How to use Automapper with Autofac

Here's one I made earlier:

public class YourAutofacModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        //Also register any custom type converter/value resolvers
        builder.RegisterType<CustomValueResolver>().AsSelf();
        builder.RegisterType<CustomTypeConverter>().AsSelf();

        builder.Register(context => new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<MyModel MyDto>;
            //etc...
        })).AsSelf().SingleInstance();

        builder.Register(c =>
        {
            //This resolves a new context that can be used later.
            var context = c.Resolve<IComponentContext>();
            var config = context.Resolve<MapperConfiguration>();
            return config.CreateMapper(context.Resolve);
        })
        .As<IMapper>()
        .InstancePerLifetimeScope();
    }
}

In the global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        var builder = new ContainerBuilder();

        builder.RegisterModule<MyAutofacModule>();
        // Register anything else needed

        var container = builder.Build();

        // MVC resolver
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        // API Resolver
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    }
}

Then all you need to do is inject IMapper


There is also a nuget-package that does all of that for you.

All you need to do is to call an extension method on the ContainerBuilder and pass in the assemblies, that should be scanned for AutoMapper types.

var containerBuilder = new ContainerBuilder();
containerBuilder.AddAutoMapper(typeof(MvcApplication).Assembly);
// more registrations here

You can find it here. You can find an official example in the AutoMapper docs as well.

Edit: There are samples for ASP.NET Core and Console-Applications here.