My current project with assemblies for the domain model, MVC web application, and unit tests. How can I set up the AutoMapper configuration so that all assemblies reference
I tried the code above, but could not get it to work. I modified it a little bit as follows below. I think all that's left to do is to call it via a Bootstrapper from Global.asax. Hope this helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoMapper;
namespace Automapping
{
public class AutoMappingTypePairing
{
public Type SourceType { get; set; }
public Type DestinationType { get; set; }
}
public class AutoMappingAttribute : Attribute
{
public Type SourceType { get; private set; }
public AutoMappingAttribute(Type sourceType)
{
if (sourceType == null) throw new ArgumentNullException("sourceType");
SourceType = sourceType;
}
}
public static class AutoMappingEngine
{
public static void CreateMappings(Assembly a)
{
IList autoMappingTypePairingList = new List();
foreach (Type t in a.GetTypes())
{
var amba = t.GetCustomAttributes(typeof(AutoMappingAttribute), true).OfType().FirstOrDefault();
if (amba != null)
{
autoMappingTypePairingList.Add(new AutoMappingTypePairing{ SourceType = amba.SourceType, DestinationType = t});
}
}
foreach (AutoMappingTypePairing mappingPair in autoMappingTypePairingList)
{
Mapper.CreateMap(mappingPair.SourceType, mappingPair.DestinationType);
}
}
}
}
And I use it like this to associate a source with a destination pairing:
[AutoMapping(typeof(Cms_Schema))]
public class Schema : ISchema
{
public Int32 SchemaId { get; set; }
public String SchemaName { get; set; }
public Guid ApplicationId { get; set; }
}
Then to Create the mappings automagically, I do this:
Assembly assembly = Assembly.GetAssembly(typeof([ENTER NAME OF A TYPE FROM YOUR ASSEMBLY HERE]));
AutoMappingEngine.CreateMappings(assembly);