Mapster
Mapster copied to clipboard
Generated Mapster.Tool mappers fails Dependency Injection
Problem
I'm working on a project that encodes and decodes a hash for primary keys (according to https://hashids.org/). However when generating mapper source files that uses Dependency Injection in the mapper config the generated mapper class fails with the exception:
Mapping must be called using ServiceAdapter
Reading the source there is no ServiceProvider
set in the parameters of MapContext.Current
for source generated mappers calls like ServiceMapper
does for runtime generated mappers:
public override TDestination Map<TDestination>(object source)
{
using var scope = new MapContextScope();
scope.Context.Parameters[DI_KEY] = _serviceProvider;
return base.Map<TDestination>(source);
}
How can this problem be solved?
My Setup
Project .csproj (here copied from Wiki)
<Target Name="Mapster" AfterTargets="AfterBuild">
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet tool restore" />
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster mapper -a "$(TargetDir)$(ProjectName).dll"" />
</Target>
Mapper interface
[Mapper]
public interface IMyDataMapper : IMapper<MyDataEntity, MyDataDTO>
{
}
Mapper config
internal class MyDataDTOMapperConfig : IRegister
{
public void Register(TypeAdapterConfig config)
{
config.NewConfig<MyDataEntity, MyDataDTO>()
Map(dest => dest.Id, src => MapContext.Current.GetService<IHashids>().Encode(src.Id));
config.NewConfig<MyDataDTO, MyDataEntity>()
.Map(dest => dest.Id, src => MapContext.Current.GetService<IHashids>().DecodeSingle(src.Id));
}
}
@Geestarraw Do you happen to be using ASP.NET Core in this case?
Possibly same issue as #519
@andrerav Yes, ASP.NET Core 6.
@Geestarraw Alright, thank you for confirming. Let's continue the discussion on #519.