簡體   English   中英

如何使用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不是GenericTypeDefinition。 只能在Type.IsGenericTypeDefinition為true的類型上調用MakeGenericType。

我不確定此錯誤的含義以及如何解決? 有人可以指導我這里發生了什么嗎?

好了,終於找到了問題所在。 問題是,默認情況下,DapperExtensions將在與Model POCO類相同的程序集中掃描您編寫的所有自定義映射器。 就我而言,它是DataTransferObjects程序集。

我的Mapper類存在於Repository程序集中,與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
 });

如上設置后,我的代碼開始工作。 這在任何地方都沒有真正記載,我花了一些時間才弄清楚。 希望它可以幫助遇到同樣問題的其他人。

請注意,如果您使用異步實現,則需要使用DapperAsyncExtensions注冊映射程序集:

DapperExtensions.DapperAsyncExtensions.DefaultMapper = typeof (ServiceMapper);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM