Afraz Ali
Afraz Ali

Reputation: 2752

How to setup Dapper Extensions custom mapping with Structuremap?

I am using Dapper Extensions for building my repositories in an MVC app that is configured to use Structuremap. For one of the Models, I need to create a custom mapping to ignore a field.

public class ServiceMapper : ClassMapper<Service>
{
    public ServiceMapper()
    {
        //Ignore this property entirely
        Map(x => x.IsRunningNormally).Ignore();

        //optional, map all other columns
        AutoMap();
    }
}

Now to invoke this mapper, I need to set it up, I am calling this line of code in the constructor of my repository.

            DapperExtensions.DapperExtensions.DefaultMapper = typeof(ServiceMapper);

As soon as I hit this line, Structuremap tries to resolve the type and throws me exception:

ServiceMonitor.Infrastructure.ServiceMapper is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.

I am not sure what this error means and how to resolve it? Can anyone please guide me as to what is going on here?

Upvotes: 1

Views: 5604

Answers (2)

wolszakp
wolszakp

Reputation: 1179

Please notice, that if you are using async imnplementations you need to register mapping assemblies using DapperAsyncExtensions:

DapperExtensions.DapperAsyncExtensions.DefaultMapper = typeof (ServiceMapper);

// Tell Dapper Extension to scan this assembly for custom mappings
DapperExtensions.DapperAsyncExtensions.SetMappingAssemblies(new[]
{
   typeof (ServiceMapper).Assembly
});

Upvotes: 1

Afraz Ali
Afraz Ali

Reputation: 2752

Ok so finally figured out the problem. The issue is that by default DapperExtensions will scan for any custom mappers that you have written, in the same assembly as your Model POCO classes. In my case it was the DataTransferObjects assembly.

My Mapper class was present in Repository assembly which is different from the DTOs assembly.

I needed to tell Dapper Extensions to scan this assembly for custom mappings:

 DapperExtensions.DapperExtensions.DefaultMapper = typeof (ServiceMapper);

 // Tell Dapper Extension to scan this assembly for custom mappings
 DapperExtensions.DapperExtensions.SetMappingAssemblies(new[]
 {
     typeof (ServiceMapper).Assembly
 });

Once I set up like above, my code started working. This is not really documented anywhere and took me a while to figure it out. Hope it helps someone else having the same issue.

Upvotes: 2

Related Questions