Can I get AutoMapper to return the same object som

2019-07-21 02:14发布

问题:

I've been using AutoMapper to map between an interface and a concrete implementation of that interface. I assumed that if the type that I passed in to AutoMapper's Map<TDestination> method was the same as the return type, then the original object would be returned (as a sort of short-circuiting operation). My assumption was wrong: indeed, after looking I noticed the documentation for that method explicitly states:

Execute a mapping from the source object to a new destination object. The source type is inferred from the source object. (bold emphasis mine)

I knocked-up this quick console app just to verify:

using System;
using AutoMapper;

namespace ConsoleApplication
{
    class Program
    {
        interface IFoo
        {
            string Bar { get; }
        }

        class Foo : IFoo
        {
            public string Bar { get; set; }
        }

        static void Main(string[] args)
        {
            Mapper.CreateMap<IFoo, Foo>();
            IFoo a = new Foo { Bar = "baz" };
            Foo b = Mapper.Map<Foo>(a);
            Console.WriteLine(Object.ReferenceEquals(a, b));  // false
        }
    }
}

Now that I know about this behaviour I can optimize around it for my particular use-case, but I was wondering if there is an alternate way of using AutoMapper whereby it will "short-circuit" in the way described above (ie. give me back the original object if the type is the same as the target type that I want)?

回答1:

You can use Mapper.Map<TSource,TDestination>(source, destination) overload.

 Foo b = new Foo();
 Mapper.Map<IFoo,Foo>(a,b);

AutoMapper will use b and not build a new object. Overall you can use a wrapper around Mapper.Map, this alternative way can be better (not tested):

public class MyMapper
{

        public static TDestination Map<TDestination>(object source) where TDestination : class
        {
            if(source is TDestination)
            {
                return (TDestination) source; //short-circuit here
            }

            return Mapper.Map<TDestination>(source);
        }


        public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
        {
            return Mapper.Map<TSource, TDestination>(source, destination);
        }
}


标签: c# AutoMapper