« Mapster » : différence entre les versions
Apparence
Ligne 44 : | Ligne 44 : | ||
dotnet add package Mapster.DependencyInjection | dotnet add package Mapster.DependencyInjection | ||
</kode> | </kode> | ||
<filebox fn='Program.cs'> | <filebox fn='Program.cs'> | ||
services.AddSingleton(TypeAdapterConfig.GlobalSettings); | services.AddSingleton(TypeAdapterConfig.GlobalSettings); | ||
services.AddScoped<IMapper, ServiceMapper>(); | services.AddScoped<IMapper, ServiceMapper>(); | ||
</filebox> | |||
<filebox fn='MyService.cs'> | |||
public class MyService(IMapper mapper) | |||
{ | |||
public void Do() | |||
{ | |||
var itemDto = mapper.Map<ItemDto>(item); | |||
} | |||
} | |||
</filebox> | </filebox> | ||
Version du 18 janvier 2025 à 23:07
Links
Mapping
// create destination from data from source
var destination = source.Adapt<Destination>();
// update destination with data from source
source.Adapt(destination);
|
Configuration
// global config
TypeAdapterConfig.GlobalSettings.Default.IgnoreNullValues(true);
// config the mapping from Item to ItemDto
TypeAdapterConfig<Item, ItemDto> // src, dest
.NewConfig() // create new map config (overwrite existing ones)
.ForType() // OR create a map config if no one exists, otherwise append to th existing one
.Ignore(dest => dest.Prop1) // do not map Prop1
.Map(dest => dest.Prop2, src => $"{0} {1}", src.Prop2, src.Prop3)); // custom mapping for Prop2
|
IRegister
Program.cs |
// scan the assembly to get the classes implementing IRegister
TypeAdapterConfig.GlobalSettings.Scan(typeof(ItemMappingRegister).Assembly);
|
MappingRegisters/ItemMappingRegister.cs |
public class ItemMappingRegister : IRegister
{
public void Register(TypeAdapterConfig config) => config.NewConfig<CreateUpdateItemRequest, Item>();
}
|
Dependency Injection
![]() |
Useful is you migrate from Automapper to Mapster and you do not want to change your code. |
dotnet add package Mapster.DependencyInjection |
Program.cs |
services.AddSingleton(TypeAdapterConfig.GlobalSettings);
services.AddScoped<IMapper, ServiceMapper>();
|
MyService.cs |
public class MyService(IMapper mapper)
{
public void Do()
{
var itemDto = mapper.Map<ItemDto>(item);
}
}
|
Installation
dotnet add package Mapster |