Skip to content

Instantly share code, notes, and snippets.

@mkmurray
Created April 23, 2011 16:08
Show Gist options
  • Save mkmurray/938741 to your computer and use it in GitHub Desktop.
Save mkmurray/938741 to your computer and use it in GitHub Desktop.
ITypeMapper class for custom AutoMapper mappings to be found and wired up conventionally by the IOC container.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoMapper;
using Blah.Blah;
using Blah.Blah.Bootstrap;
using Microsoft.Practices.ServiceLocation;
namespace Blah.Blah.BootstrapperTasks
{
public class ConfigureAutoMapperTask : IBootstrapperTask
{
private readonly IServiceLocator _serviceLocator;
public ConfigureAutoMapperTask(IServiceLocator serviceLocator)
{
_serviceLocator = serviceLocator;
}
public int Order
{
get { return 0; }
}
public void Execute()
{
Func<Type, Type, MethodInfo> infoFunc = (ts, td) => typeof(Mapper).GetMethod("CreateMap", new Type[0]).MakeGenericMethod(ts, td);
_serviceLocator.GetAllInstances(typeof(ITypeMapper))
.Each(mapper =>
{
var typeConverter = mapper.GetType();
typeConverter.GetInterfaces()
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ITypeMapper<,>))
.Each(i =>
{
Type[] args = i.GetGenericArguments();
var map = infoFunc(args[0], args[1]).Invoke(null, null);
i.GetMethod("SetupMap").Invoke(mapper, new[] { map });
});
});
}
}
}
using AutoMapper;
namespace Blah.Blah
{
public interface ITypeMapper<TSource, TDestination> : ITypeMapper
{
void SetupMap(IMappingExpression<TSource, TDestination> map);
}
public interface ITypeMapper {}
}
using System;
using AutoMapper;
namespace Blah.Blah.Extensions
{
public static class ObjectExtensions
{
public static object Map(this object source, Type destinationType)
{
if (destinationType.IsValueType && source == null)
{
return Activator.CreateInstance(destinationType);
}
return Mapper.DynamicMap(source, source.GetType(), destinationType);
}
public static T DynamicMap<T>(this object source)
{
return (T)source.Map(typeof(T));
}
}
}
@statianzo
Copy link

Looks familiar. :-)

One thing to be aware of with this implementation of Map/DynamicMap is that it will use the runtime type of whatever your source object is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment