public class FSharpOptionObjectMapper : IObjectMapper | |
{ | |
public object Map(ResolutionContext context, IMappingEngineRunner mapper) | |
{ | |
var sourceValue = ((dynamic) context.SourceValue); | |
return (sourceValue == null || OptionModule.IsNone(sourceValue)) ? null : sourceValue.Value; | |
} | |
public bool IsMatch(ResolutionContext context) | |
{ | |
var isMatch = context.SourceType.IsGenericType && | |
context.SourceType.GetGenericTypeDefinition() == typeof (FSharpOption<>); | |
if (context.DestinationType.IsGenericType) | |
{ | |
isMatch &= context.DestinationType.GetGenericTypeDefinition() != typeof(FSharpOption<>); | |
} | |
return isMatch; | |
} | |
} | |
/// | |
/// in your setup / configuration of AutoMapper | |
/// | |
var allMappers = AutoMapper.Mappers.MapperRegistry.AllMappers; | |
AutoMapper.Mappers.MapperRegistry.AllMappers = () => allMappers().Concat(new List<IObjectMapper> | |
{ | |
new FSharpOptionObjectMapper() | |
}); | |
/// | |
/// Testing this | |
/// | |
[Test] | |
public void FSharpOptionObjectMapper() | |
{ | |
Mapper.CreateMap<SourceWithOption, DestinationWithNoOption>(); | |
var allMappers = AutoMapper.Mappers.MapperRegistry.AllMappers; | |
AutoMapper.Mappers.MapperRegistry.AllMappers = () => allMappers().Concat(new List<IObjectMapper> | |
{ | |
new DustAutomapper.FSharpOptionObjectMapper() | |
}); | |
var id = new StudioId(); | |
var source1 = new SourceWithOption | |
{ | |
Standard = "test", | |
PropertyUnderTest = new FSharpOption<StudioId>(id) | |
}; | |
var source2 = new SourceWithOption | |
{ | |
Standard = "test" | |
}; | |
var result1 = Mapper.Map<SourceWithOption, DestinationWithNoOption>(source1); | |
Assert.AreEqual("test", result1.Standard, "basic property failed to map"); | |
Assert.AreEqual(id, result1.PropertyUnderTest, "TypeTypeConverter on BaseIdentiy didn't work as expected"); | |
var result2 = Mapper.Map<SourceWithOption, DestinationWithNoOption>(source2); | |
Assert.AreEqual("test", result1.Standard, "basic property failed to map"); | |
Assert.IsNull(result2.PropertyUnderTest, "TypeTypeConverter for null failed"); | |
} | |
public class SourceWithOption | |
{ | |
public string Standard { get; set; } | |
public FSharpOption<StudioId> PropertyUnderTest { get; set; } | |
} | |
public class DestinationWithNoOption | |
{ | |
public string Standard { get; set; } | |
public StudioId PropertyUnderTest { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment