tags:

views:

42

answers:

1

I have a SearchService with a Search() method that retrieves an IEnumerable<Search> from a repository. These Search objects come directly from LINQ To SQL. Next I'm using AutoMapper to convert those Search types into SearchModel types (and later they get passed into a controller, for example).

var searches = searchRepository.GetByUserID(userID);        
var models = Mapper.Map<IEnumerable<Search>, IEnumerable<SearchModel>>(searches);

The problem is that Search has a property DateCreated which is a UTC DateTime. I need to correct the date based on the logged-in user for their local time zone. I could do this with a foreach inside the service, like so:

var searches = searchRepository.GetByUserID(userID);   

foreach (var search in searches)
{
    search.DateCreated = search.DateCreated.ToTimezone(userTimezoneID);
}

var models = Mapper.Map<IEnumerable<Search>, IEnumerable<SearchModel>>(searches);

While this works (and may be the only option), I'd like to make use of AutoMapper's IValueFormatter. I have a few other value formatters for things like relative time, for example.

My question is: can this be done? I'm unsure because I guess I'd need to pass along additional information to AutoMapper so it knew which time zone ID to use to make the conversion.

I was also trying to avoid getting this from the Search -> User relationship, as I'd have it stored in a cookie when the user logs in (and would like to avoid the database JOIN in retrieving it). How can I pass this time zone ID to AutoMapper so it can do custom mapping per user?

+2  A: 

I think you're going to want to use AutoMapper with a Custom Resolver. Your custom resolve will support dependency injection. It works best if you are using an IoC, but you could inject your user into the resolver and perform appropriate logic within the ResolveCore method. Here's a rough example:

private readonly IUserContext _userContext;

public MyResolver(IUserContext userContext)
{
 _userContext = userContext;
}

protected override String ResolveCore(object source)
{                    
 // Calculate display date based on user context
    return TheDate;
}

Definitely check out the Custom Resolver docs though.

I hope it helps.

Ben Griswold