Add AutoMapper profile with Umbraco

As you might already know, Umbraco uses AutoMapper to map objects from one class to another and so can you. However you’ll need to add your profiles to AutoMapper in a specific way. Indeed, as the documentation states, you should configure AutoMapper only once per app domain, so if you just call the “Initialize” method on the “Mapper” static class in a custom application handler, you’d break Umbraco as you would override its AutoMapper configuration.

So the question is: “how to add AutoMapper profiles to the ones already defined in Umbraco?”. The response to this question can be found in this file. As you can see, Umbraco gives you the possibility to inherit from the “MapperConfiguration” class to add profile to AutoMapper like so:

Now, this approach is cool, however, if you have a big application containing a lot of profiles, you’ll have to add them one by one in this function. This could be fixed by implementing something like this:

This way, when the application has started, this piece of code analyses the current assembly to find all the classes that inherit from “Profile” and add them to the “AutoMapper” profiles.

Note that this implementation does not really care about performances. Indeed, all these chained LINQ methods actually perform more loops than necessary. If you care about performances, it might be better not to use LINQ and use a good old fashioned single “foreach” loop.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.