Mapster not mapping
I'm using Mapster with DI and I'm trying to map objects that I receive from WS. I was following this guide https://github.com/MapsterMapper/Mapster/wiki/Dependency-Injection#mapping
I register TypeAdapterConfig, and ServiceMapper
var config = new TypeAdapterConfig();
services.AddSingleton(config);
services.AddScoped<IMapper, ServiceMapper>();
Blacklist class contains collection of Cards but webservice returns array of long, that I remap to object.
public class BlacklistMapper : IRegister
{
void IRegister.Register(TypeAdapterConfig config)
{
config.NewConfig<long, Internal.BlacklistCard>()
.Map(dest => dest.Cuid, source => source);
config.NewConfig<SzWebService.BlackList, Internal.Blacklist>()
.Map(dest => dest.Id, source => source.iBlacklistId)
.Map(dest => dest.Crc, source => source.iBlackListCRC)
.Map(dest => dest.Cards, source => source.lCuid);
}
}
Inject mapper in the constuctor
private readonly IMapper _mapper;
public Service(IMapper mapper)
{
_logger = logger;
}
And finally call it like so
_mapper.Map<Blacklist>(response.mBlackListData)
The result is always object with default values
Solution 1:
Step 1 - Create the configuration via implementing IRegister
public class BlacklistMapper : IRegister
{
void Register(TypeAdapterConfig config)
{
config.NewConfig<SzWebService.BlackList, Internal.Blacklist>()
.Map(...)
.Map(...);
}
}
Step 2 - Register the configuration
You can either register the configuration explicitly:
var config = new TypeAdapterConfig();
// Explicitly apply a specific configuration
config.Apply(new BlackListMapper());
services.AddSingleton(config);
services.AddScoped<IMapper, ServiceMapper>();
or let Mapster scan your assemblies for IRegister
implementations:
// Scan & apply IRegisters automatically.
config.Scan(Assembly.GetExecutingAssembly());