I recently created a set of DTO objects to complement the domain entities we use for our data access layer for a new project we’re working on. I immediately set out to write a mapping utility. After a bit of thought pondering the complexity of the problem I decided to look around on the magical internets to see what options were available.
Came across Automapper. This is a perfect match for my needs:
AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to match up source to destination values. Currently, AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.
It was quick to setup, and painless to use. First define your object to object mappings:
It’s important to note that if your source object contains nested objects – a mapping for each nested object must also be defined. This goes on recursively through nested objects. My domain Application object contains some numerous sub objects – Map, Layer etc. In this case rather than establish mappings for these child objects – I removed these objects from my DTO as the client consuming these objects would never need that data. This also keeps the size of any data possibly being serialized down. Automapper dealt with this automatically.
I’ve only scratched the surface of what Automapper can do. Next step is to define unit test coverage using the configuration validation, but it’s sleep time now… =)