This is driving me nuts... I have been trying to pass a variable to a custom resolver, but it seems impossible to do.
I am currently using the following approach, but the value that is passed to the Custom Resolvers constructor is always an empty string "" even though I specifically register a new mapping to overwrite the existing one (See controller)
Custom Resolver
public class DueDateResolver : ValueResolver<Task, string>
{
public string DateFormat = "MMM dd, @ h:mm tt";
public DueDateResolver(string dateFormat)
{
// If no date format is pa开发者_开发知识库ssed use the default
if (!String.IsNullOrEmpty(dateFormat))
{
DateFormat = dateFormat;
}
}
}
Controller
// <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);
}
Mappings
The Register() method is done at the global.asa level. The other method above is called in my controller.
/// <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("")));
}
I would create the mapping once then leave it alone. Create a context object with your resolver parameter, use DI/IoC to inject it into the resolver, and update it from the controller before executing the mapper.
精彩评论