这让我疯狂......我一直试图将变量传递给自定义解析器,但似乎无法做到。
我目前正在使用以下方法,但传递给Custom Resolvers构造函数的值始终为空字符串“”,即使我专门注册了一个新映射来覆盖现有映射(请参阅控制器)
自定义解析器
public class DueDateResolver : ValueResolver<Task, string>
{
public string DateFormat = "MMM dd, @ h:mm tt";
public DueDateResolver(string dateFormat)
{
// If no date format is passed use the default
if (!String.IsNullOrEmpty(dateFormat))
{
DateFormat = dateFormat;
}
}
}
控制器
// <summary>
/// Ajax Method for filtering tasks by Date Range
/// </summary>
/// <param name="dateFilter">The date filter label ["Day", "Week", "Month", "All", "Last 30 Days"]</param>
/// <returns>List of task objects</returns>
[HttpGet]
public JsonResult GetTasksByDateRange(DateFilters dateFilter)
{
RegisterMaps.RegisterTaskViewModel(dateFilter.ToString());
List<Task> tasks = taskService.GetFilteredTasksByDate(dateFilter, "chobojunk@gmail.com");
List<TaskTableViewModel> viewModelList = Mapper.Map<List<Task>, List<TaskTableViewModel>>(tasks);
return Json(viewModelList, JsonRequestBehavior.AllowGet);
}
映射
Register()方法在global.asa级别完成。上面的另一种方法在我的控制器中调用。
/// <summary>
/// Special case where I need to pass in a parameter
/// </summary>
public static void RegisterTaskViewModel(string dateFilter)
{
Mapper.CreateMap<Task, TaskTableViewModel>().ForMember(dest => dest.DueDate,
opt => opt.ResolveUsing<DueDateResolver>().ConstructedBy(() => new DueDateResolver(dateFilter)));
}
public static void Register()
{
Mapper.CreateMap<Task, TaskTableViewModel>().ForMember(dest => dest.DueDate,
opt => opt.ResolveUsing<DueDateResolver>().ConstructedBy(() => new DueDateResolver("")));
}
答案 0 :(得分:0)
我会创建一次映射然后不管它。使用解析器参数创建上下文对象,使用DI / IoC将其注入解析器,并在执行映射器之前从控制器更新它。