AutoMapper feature: interfaces and dynamic mapping

In this post, I’ll highlight two features new in the 0.3 release: mapping to interfaces and dynamic mapping.  Both of these come up in rather interesting scenarios.

Mapping to interface destinations

In some messaging scenarios, the message itself is not a DTO type, but rather an interface.  In these cases, it’s rather annoying to create a derived type just for every interface-based message in your system.  Instead, we can use AutoMapper to do the work for us.  Suppose we have these source types:

public class OrderForm
    public Customer Customer { get; set; }

public class Customer
    public string Name { get; set; }

These can be from a complex domain model, external system, or business objects.  We now need to interface with some external system, but they’ve defined their message contracts as interfaces.  It’s not completely out of the question, but I run into this from time to time.  It might require some message like:

public interface ICreateOrderMessage
    string CustomerName { get; set; }

In this case, the destination type is an interface, and its member is a flattened version of our domain model.  Here’s our mapping code:

Mapper.CreateMap<OrderForm, ICreateOrderMessage>();


var order = new OrderForm
        Customer = new Customer {Name = "Bob Smith"}

var message = Mapper.Map<OrderForm, ICreateOrderMessage>(order);

message.CustomerName.ShouldEqual("Bob Smith");

I create a type map from the source type (OrderForm) to the destination interface type.  An implementation ICreateOrderMessage doesn’t exist anywhere in our system.  I create the order form, and map to the message with the Mapper.Map call.  At runtime, AutoMapper creates a dynamic proxy type for ICreateOrderMessage, using the default property behavior for getters and setters.  Underneath the covers, I used LinFu to create the proxy type.  Using this feature does not require any additional references, however, as the LinFu assembly is merged into the AutoMapper assembly.

Dynamic mapping

In most mapping scenarios, we know the type we’re mapping to at compile time.  In some cases, the source type isn’t known until runtime, especially in scenarios where I’m using dynamic types or in extensibility scenarios.  To support these scenarios, but still preserve the safety of configuration validation, AutoMapper 0.3 includes a way to dynamically map from a source to a destination type.  No configuration is needed, just one call to AutoMapper.  I’ll still try to map to the interface destination:

public interface ICreateOrderMessage
    string CustomerName { get; set; }

And instead of creating a OrderForm in the previous example, I’ll use a dynamic type:

var order = new {CustomerName = "Bob Smith"};

var message = Mapper.DynamicMap<ICreateOrderMessage>(order);

message.CustomerName.ShouldEqual("Bob Smith");

The DynamicMap call creates a configuration for the type of the source object passed in to the destination type specified.  If the two types have already been mapped, AutoMapper skips this step (as I can call DynamicMap multiple times for this example).  To be safe, AutoMapper will validate the configuration for a dynamic map the first time executed, as it tends to give better messages than a mapping exception.

With DynamicMap, you don’t have the luxury of configuring the mapping, but at this point, you’ve also lost the benefits of a single AssertConfigurationIsValid call.  In the DynamicMap side, I could lower the bar quite a bit and not do any mapping validation, but I’d rather not as its intended use is a very specific scenario.  The ideal case is to configure your mappings up front, for much better testability.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in AutoMapper. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Pavel Korotkov

    Hi, Bogardj
    Recently I started to playing with AutoMapper and got very enthusiastic about it. It’s really powerful and elegant, I like it.
    The question (might be trivial) is that how I can create a dynamic proxy for the given interface
    public interface ITest
    Int32 Id { get; }
    String Name { get; }
    If I attribute the properties with set accessors everything works fine with lines
    var tc = new { Id = 1, Name = “Bob” };
    var ctc = Mapper.DynamicMap(tc);
    var id = ctc.Id;
    When I have only get accessors an exception is thrown: “KeyNotFoundException. The given key was not present in the dictionary.” Does my setup need some tuning?
    Thanks, PK

  • Nathan Alden

    I am running into the same issue as Pavel. I have a read-only entity interface called IUser. I need each getter to return the anonymous type’s values.

  • @Nathan

    Right now, the interface needs setters. With the dynamic proxy juju going on underneath the covers, it’s the only way I could get it to work right where it actually performs mapping (as opposed to just a pass-through implementation).

    Maybe I could create a derived interface type that DOES include setters at runtime, but man, that’ll be tough. Are you sure you can’t just create an interface w/ setters?

  • Sadia

    Hi Jimmy,
    I need your help. I have been utilizing automapper for my application. I have recently come across an issue. I have seen intermittent expeception in mapping entity objects with DTO objects. It throws the famous Automapper.MappingException and says it is trying to map entityObject1 to DTOObject1 and throws an expections there. After pushing out a new fresh build with no change it started working fine.

    Please help me out how can I further investigate or resolve this issue.


  • @Sadia

    Would you mind posting this on the AutoMapper mailing list? I’ll be able to track this issue much better there.



  • I’m running into the same issue as Nathan and Pavel.

    Why don’t you create the “proxy” entities using Reflection.Emit with both getters and setters, and have those emitted entity classes implement the interface? Doing this with Relfection.Emit  should not be too hard really, and it would also not require merging a proxying library under the hood while solving the issue at hand (because all you would the do is to substitute the interface type for the type of the emitted class whenever you get the interface as type, all the rest of AutoMapper would do its magic as before).

    • Anonymous

      Being totally honest here, I would love to see a pull request on this one!

  • veljkoz

    This is a great neat feature… if only I could mark the proxy to be [Serializable] ?

    • jbogard

      Open a GitHub issue for it and I’ll take a look!

      • veljkoz

        #534 opened… and closed after I figured out there’s no way one could deserialize that :-)

  • Michal


    What if destination interface doesn’t have setter but still I don’t want to create concret type? The contracts I use are plain messages send to masstransit and i don’t need setters there. I know Masstransit handles it somehow :)

    • jbogard

      Nope, this is not supported. Create a GH issue please!

  • Manoj Pant

    List people = AutoMapper.Mapper.DynamicMap<IDataReader, List>(sourceDataTable.CreateDataReader());

    What code is use in place of above code for DynamicMap of Datatable into list
    into automapper 4.2.

    • jbogard

      Can you create a GitHub issue?