AutoMapper: writing a custom IValueResolver for Gravatar


I’m a big fan of Jimmy Bogard’s AutoMapper – a handy little tool for fluently mapping your domain model objects to presentation model objects.

This week, I added Gravatar support to a small side-project I’m working on. For those that don’t know, Gravatar is a globally recognized avatar with a URL based on the MD5 hash of your e-mail address, e.g.:

Any site that knows your e-mail address can therefore generate your Gravatar URL and show your profile pic. If you’re using AutoMapper, mapping an e-mail address to a Gravatar URL is a perfect case for a custom IValueResolver, e.g.:

Mapper.CreateMap<User, UserProfile>()    .ForMember(p => p.Username, opt => opt.MapFrom(u => u.Username))    .ForMember(p => p.About, opt => opt.MapFrom(u => u.Profile.About))    .ForMember(p => p.Location, opt => opt.MapFrom(u => u.Profile.Location))    .ForMember(p => p.Url, opt => opt.MapFrom(u => u.Profile.Url))    .ForMember(p => p.DisplayImage,               opt => opt.ResolveUsing<GravatarUrlResolver>()                         .FromMember(u => u.Profile.Email));

You can download my implementation here: GravatarUrlResolver.cs and tests (of course) here: GravatarUrlResolverTests.cs