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..