I'm upgrading AutoMapper in a project, converting from the static Mapper.CreateMap
to the new way and injecting a IMapper
where I need to map.
This is going great except for one use case. I have several ITypeConverter
s for complex mapping which are using the Mapper.Map
function. How can I fix this? Below is the code I'm using at the moment.
The static Mapper.Map
can't find my defined mappings because the're not being created using the static method.
public partial class ApplicationMappingsProfile
{
private void RegisterMappings()
{
CreateMap<Application, AppDto>()
.ConvertUsing<ApplicationTypeConverter>();
}
}
private class ApplicationTypeConverter : ITypeConverter<App, AppDto>
{
public AppDto Convert(ResolutionContext context)
{
var src = context.SourceValue as App;
if (src == null)
{
return null;
}
var dto = Mapper.Map<App, AppDto>(src);
dto.property = Mapper.Map<Property>(src.SomeProperty);
return result;
}
}
AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.
AutoMapper is a ubiquitous, simple, convention-based object-to-object mapping library compatible with.NET Core. It is adept at converting an input object of one kind into an output object of a different type. You can use it to map objects of incompatible types.
The ResolutionContext
contains a reference to the current Mapping engine. Switch the Mapper.Map
with context.Engine.Mapper.Map
and you're good to go.
public partial class ApplicationMappingsProfile
{
private void RegisterMappings()
{
CreateMap<Application, AppDto>()
.ConvertUsing<ApplicationTypeConverter>();
}
}
private class ApplicationTypeConverter : ITypeConverter<App, AppDto>
{
public AppDto Convert(ResolutionContext context)
{
var src = context.SourceValue as App;
if (src == null)
{
return null;
}
var dto = Mapper.Map<App, AppDto>(src);
dto.property = context.Engine.Mapper.Map.Map<Property>(src.SomeProperty);
return result;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With