Mapper Function Using Reflection

One step forwards, one step back.  Such is the situation jumping between development shops.  Different teams evolve differently based on pain points, needs, and managerial support, and while a team may be lightyears ahead in one aspect (IE high performance asynchonous code) they can be lagging behind in other areas.

One of the things I *loved* about my last position, especially being a team lead on a relatively small team, was that I could easily get agreement and introduce new technologies.  Two of the most beneficial ones I’ve had the pleasure of implementing were Ninject and Automapper, the former being an excellent dependency injection tool to aid in unit testing, and the latter being an excellent tool to save you the pain of writing all that plumbing code between your database entities, DTOs.

Anyways, I found myself in a situation earlier where I found myself tired of writing line-by-line (believe me, after using AutoMapper you really don’t want to go back) so I came up with a little solution that uses generics and reflection:

        private void MapGlobalConfigData(T source, object dest)
        {
            var sourceType = source.GetType();
            var destType = dest.GetType();

            var sourceProps = sourceType.GetProperties();
            var destProps = destType.GetProperties();

            var commonProps = from sp in sourceProps
                                   join dp in destProps on new { sp.Name, sp.PropertyType } equals
                                       new { dp.Name, dp.PropertyType }
                                   select new { sp, dp };

            foreach (var property in commonProps)
            {
                property.dp.SetValue(dest, property.sp.GetValue(source, null), null);
            }

        }

The function itself is pretty straightforward. Using reflection, it looks for properties with common names and data types between your source and destination object, and pushes a reference to the corresponding properties in a collection.

I’m still battle-testing it, but thus far it looks like a quick and simple alternative to AutoMapper, as long as you’re *verY* careful about how you’re using it.

Why not use AutoMapper? It’s a hard sell to the architecture team 🙂 This is a great interim solution.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s