Luca
Luca

Reputation: 75

Automapper - Dynamic type mapping

When I try to map with automapper a class generated at run-time.

AssemblyName asmName = new AssemblyName(string.Format("{0}_{1}", "tmpAsm", Guid.NewGuid().ToString("N")));
AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = asmBuilder.DefineDynamicModule("core");
TypeBuilder typeBuilder = GetTempModule().DefineType("MyDynamicClass", TypeAttributes.Public);
Type proxy = typeBuilder.CreateType();
var mc = new MapperConfiguration(cfg =>
{
    cfg.CreateMap(proxy, typeof(MyViewModel));
});

var mapper = mc.CreateMapper();
mapper.Map<MyViewModel>(Activator.CreateInstance(proxy));

I get the following error:

AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping.

Despite of what the error message says, the mapping has been decleared as you can see. Any suggestion?

Upvotes: 2

Views: 660

Answers (1)

Timothy Ghanem
Timothy Ghanem

Reputation: 1616

Try using:

TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicClass", TypeAttributes.Public);

Instead of:

TypeBuilder typeBuilder = GetTempModule().DefineType("MyDynamicClass", TypeAttributes.Public);

Also, check the version of AutoMapper that you are using: i tested on 6.1.1.0

Upvotes: 0

Related Questions