Search code examples
c#asp.net-web-apiasp.net-web-api2automapperautofac

How to use Automapper with Autofac


I've upgraded to the latest version of AutoMapper (9.0) and I've changed the static configuration to:

public static IMapper RegisterAutoMapper()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<MyModel MyDto>;
        //etc...
   });
  
   var mapper = config.CreateMapper();
   return mapper;
}

Using the previous static API I used to do the following in Global.asax:

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
    AutoMapping.Map();
}

WebApiConfig.Register registers the routes and also Autofac

How do I register AutoMapper with Autofac because currently I'm getting compiler errors on such lines:

var myDto = Mapper.Map<MyModel>(model);

And the compiler error:

An object reference is required for the non-static field, method, or property 'Mapper.Map(object)'


Solution

  • 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