如何使用 Structuremap 设置 Dapper Extensions 自定义映射?

How to setup Dapper Extensions custom mapping with Structuremap?

我正在使用 Dapper Extensions 在配置为使用 Structuremap 的 MVC 应用程序中构建我的存储库。对于其中一个模型,我需要创建一个自定义映射来忽略一个字段。

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

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

现在要调用这个映射器,我需要设置它,我在我的存储库的构造函数中调用这行代码。

            DapperExtensions.DapperExtensions.DefaultMapper = typeof(ServiceMapper);

我一点击此行,Structuremap 就会尝试解析类型并抛出异常:

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

我不确定这个错误是什么意思以及如何解决?谁能指导我了解这里发生了什么?

好的,终于找到问题了。问题是,默认情况下,DapperExtensions 将在与模型 POCO classes 相同的程序集中扫描您编写的任何自定义映射器。在我的例子中,它是 DataTransferObjects 程序集。

My Mapper class 出现在与 DTO 程序集不同的存储库程序集中。

我需要告诉 Dapper Extensions 扫描此程序集以查找自定义映射:

 DapperExtensions.DapperExtensions.DefaultMapper = typeof (ServiceMapper);

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

像上面那样设置后,我的代码就开始工作了。这在任何地方都没有真正记录下来,我花了一段时间才弄明白。希望它能帮助遇到同样问题的其他人。

请注意,如果您使用 async 实现,则需要使用 DapperAsyncExtensions:

注册映射程序集
DapperExtensions.DapperAsyncExtensions.DefaultMapper = typeof (ServiceMapper);

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