Mapster icon indicating copy to clipboard operation
Mapster copied to clipboard

Generated Mapster.Tool mappers fails Dependency Injection

Open Geestarraw opened this issue 2 years ago • 4 comments

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 &quot;$(TargetDir)$(ProjectName).dll&quot;" />
  </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 avatar Apr 13 '22 17:04 Geestarraw

@Geestarraw Do you happen to be using ASP.NET Core in this case?

andrerav avatar Jan 29 '23 21:01 andrerav

Possibly same issue as #519

andrerav avatar Jan 29 '23 21:01 andrerav

@andrerav Yes, ASP.NET Core 6.

Geestarraw avatar Jan 30 '23 18:01 Geestarraw

@Geestarraw Alright, thank you for confirming. Let's continue the discussion on #519.

andrerav avatar Jan 30 '23 19:01 andrerav