0

Using Mapster with the Mapster DI package I also have a static class called MapperConfig that has a static method that does all my dto to viewmodel mapping.

 public static class MapperConfig
{
 public static void Config()
 {
   var tenantId = MapContext.Current.GetService<IConfiguration>().GetSection("MySettings").GetValue<int>("DefaultTenantId");
   _ = TypeAdapterConfig<CountyDetail, CountyVM>.NewConfig()
            .Map(d => d.Phone.Number, s => string.Format("{0:(###) ###-####}", Convert.ToInt64(s.Phone.Number)))               
            .Map(d => d.Postal, s => s.Postal.Trim())
            .IgnoreNullValues(true);
  }
}

In the past I would call this in the ConfigureServices section of the startup class. Now I am trying to use DI with to pass some configuration values into the MapperConfig file so I have created an extension method:

  public static IServiceCollection AddMapster(this IServiceCollection services, Action<TypeAdapterConfig> options = null)
    {
        var config = TypeAdapterConfig.GlobalSettings;
        config.Scan(Assembly.GetAssembly(typeof(Startup)));
        options?.Invoke(config);
        services.AddSingleton(config);
        services.AddScoped<IMapper, ServiceMapper>();
        return services;
    }

And then added that to my ConfigureServices section of the Startup class

  services.AddMapster(options =>
        {
            TypeAdapterConfig.GlobalSettings.Default.IgnoreNullValues(true);
        });

Now if I leave the call to MapperConfig.Config in the Startup.ConfigureServices method Iget an error "Mapping must be called using ServiceAdapter".

Not sure how/where that would be done..

Tarc
  • 3,214
  • 3
  • 29
  • 41
John S
  • 7,909
  • 21
  • 77
  • 145

2 Answers2

0

The line tenantId needed to move into mapping configuration.

var tenantId = MapContext.Current.GetService<IConfiguration>().GetSection("MySettings").GetValue<int>("DefaultTenantId");

For example,

TypeAdapterConfig<CountyDetail, CountyVM>.NewConfig()
     .Map(d => d.TanentId, 
          s => MapContext.Current.GetService<IConfiguration>().GetSection("MySettings").GetValue<int>("DefaultTenantId"));
lopezbertoni
  • 3,551
  • 3
  • 37
  • 53
0

Put all of your custom mapping to TypeAdapterConfig, and register TypeAdapterConfig.GlobalSetting as singleton.

services.AddSingleton(TypeAdapterConfig.GlobalSettings);
services.AddScoped<IMapper, ServiceMapper>();

Next, Register ServiceMapper to IMapper. Then you can inject IMapper to your constructor which need it.

public class SampleService 
{
    private readonly IMapper _mapper;
    public SampleService(IMapper mapper) {
        _mapper = mapper;
    }
}