![](/img/trans.png)
[英]How to mock dependencies for IValueResolver from Automapper in unit tests
[英]How to use the new IValueResolver of AutoMapper?
我不知道如何在新版本的 AutoMapper 中使用新的IValueResolver
接口。 也許我在以前版本的 AutoMapper 中使用不當......
我有很多 model 類,其中一些是使用 sqlmetal 從幾個數據庫服務器上的幾個數據庫生成的。
其中一些類具有字符串屬性PublicationCode
,它標識訂閱、報價、發票或其他任何內容屬於哪個出版物。
該出版物可以存在於兩個系統(舊系統和新系統)中的任何一個中,因此我在目標 model 類上有一個 bool 屬性,它告訴該出版物是在舊系統中還是在新系統中。
使用 AutoMapper 的舊版本(<5?),我使用了一個ValueResolver<string, bool>
它將PublicationCode
作為輸入參數,並返回一個bool
指示發布的位置(舊系統或新系統)。
使用 AutoMapper 的新版本(5+?),這似乎不再可能。 新的 IValueResolver 需要我擁有的每個源模型和目標模型組合的唯一實現,其中src.PublicationCode
需要解析為dst.IsInNewSystem
。
我只是想以錯誤的方式使用價值解析器嗎? 有沒有更好的辦法? 我想使用解析器的主要原因是我更願意將服務注入構造函數,而不必在代碼中使用DependencyResolver
等(我正在使用 Autofac)。
目前,我通過以下方式使用它:
// Class from Linq-to-SQL, non-related properties removed.
public class FindCustomerServiceSellOffers {
public string PublicationCode { get; set; }
}
這是我擁有的幾個數據 model 類之一,其中包含 PublicationCode 屬性)。 這個特定的 class 映射到這個視圖 model:
public class SalesPitchViewModel {
public bool IsInNewSystem { get; set; }
}
這兩個類的映射定義是(其中 expression 是一個 IProfileExpression),刪除了不相關的映射:
expression.CreateMap<FindCustomerServiceSellOffers, SalesPitchViewModel>()
.ForMember(d => d.IsInNewSystem, o => o.ResolveUsing<PublicationSystemResolver>().FromMember(s => s.PublicationCode));
和解析器:
public class PublicationSystemResolver : ValueResolver<string, bool>
{
private readonly PublicationService _publicationService;
public PublicationSystemResolver(PublicationService publicationService)
{
_publicationService = publicationService;
}
protected override bool ResolveCore(string publicationCode)
{
return _publicationService.IsInNewSystem(publicationCode);
}
}
以及映射器的使用:
var result = context.FindCustomerServiceSellOffers.Where(o => someCriteria).Select(_mapper.Map<SalesPitchViewModel>).ToList();
您可以通過實現IMemberValueResolver<object, object, string, bool>
並在映射配置中使用它來創建更通用的值解析器。 您可以像以前一樣提供源屬性解析功能:
public class PublicationSystemResolver : IMemberValueResolver<object, object, string, bool>
{
private readonly PublicationService _publicationService;
public PublicationSystemResolver(PublicationService publicationService)
{
this._publicationService = publicationService;
}
public bool Resolve(object source, object destination, string sourceMember, bool destMember, ResolutionContext context)
{
return _publicationService.IsInNewSystem(sourceMember);
}
}
cfg.CreateMap<FindCustomerServiceSellOffers, SalesPitchViewModel>()
.ForMember(dest => dest.IsInNewSystem,
src => src.ResolveUsing<PublicationSystemResolver, string>(s => s.PublicationCode));
所以在我這邊,我想補充一些小東西; 嘗試一下
builder.Services.AddAutoMapper(typeof(TransactionProfile).Assembly); // working
builder.Services.AddAutoMapper(x => x.AddProfile<(TransactionProfile)>()); // not working
builder.Services.AddAutoMapper(x => x.AddMaps("Outlay.Infrastructure")); // not working
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.