Saturday, February 27, 2010

I wanna be not so noisy and decoupled to AutoMapper

If you haven't read my previous article on AutoMapper, please read it first.

I just read an article on the noisiness which could be introduced with AutoMapper.

My Mapping Code is Noisy

Accordingly to that article my code:

   CustomerViewItem customerViewItem = Mapper.Map<CustomerCustomerViewItem>(customer);

is noisy code.

Why?

In few words that is because I'm coupled to the specific mapping engine and because I'm providing too much unneeded information on about how to map my objects.
Take a look on that line once again: we used Customer , but we already have customer, so we can know its type.


What to do to make it not so noisy?


In that article, that I pointed, there is proposition to change my code to:


            CustomerViewItem customerViewItem = customer.Map<CustomerViewItem>();


So, I've got interested to apply it to my previous AutoMapper article's code. As you already caught Map is just extension method for my Customer  class.


Here it is:


    public static class MappingExtentions
    {
        public static TDest Map<TDest>(this Customer customer)
        {
            return Mapper.Map<Customer, TDest>(customer);
        }
    }


Everything becomes simple if you are trying it.

2 comments:

  1. Andriy,

    That code works well, but only in context of a customer.

    Try this -- http://pastie.org/845137

    Follow the link for a nice code paste

    ReplyDelete
  2. Yes, this works just fine:

    public static TDest Map(this object customer)
    {
    return (TDest)Mapper.Map(customer, customer.GetType(), typeof(TDest));
    }

    But in this case I'll get method Map for any object like here:

    object anyObject = new object();
    anyObject.Map();

    I don't see instance of any object to be brilliant to have Map method.

    ReplyDelete