Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)'

like image 531
Ivan-Mark Debono Avatar asked Aug 16 '19 06:08

Ivan-Mark Debono


People also ask

How do I use AutoMapper to list a map?

Once you have your types, and a reference to AutoMapper, you can create a map for the two types. Mapper. CreateMap<Order, OrderDto>(); The type on the left is the source type, and the type on the right is the destination type.

Does AutoMapper support .NET 5?

AutoMapper doesn't work in asp net core 5.0.

Why would I want to integrate Autofac with automapper?

This will make Autofac be in control of all object creation within your AutoMapper profiles which is useful for external dependencies, object disposal and mocking. We were unable to load Disqus Recommendations.

What is automapper?

That is AutoMapper is an object-object mapper. It maps the properties of two different objects by transforming the input object of one type to the output object of another type.

How to use automapper with an IOC?

Well really it all depends how AutoMapper was originally setup, but if you have an IoC to hand you can simply call: Mapper.Configuration.ConstructServicesUsing(ioc.Resolve);

How to add automapper to a containerbuilder?

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. 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.


1 Answers

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

like image 50
andyb952 Avatar answered Oct 10 '22 02:10

andyb952