将Mapster与Mapster DI包一起使用,我还有一个名为MapperConfig的静态类,该类具有一个静态方法,该方法将我所有的dto都映射到viewmodel映射。
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);
}
}
过去,我会在启动类的ConfigureServices部分中将此称为。现在,我尝试使用DI来将一些配置值传递到MapperConfig文件中,因此我创建了扩展方法:
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;
}
然后将其添加到我的Startup类的ConfigureServices部分
services.AddMapster(options =>
{
TypeAdapterConfig.GlobalSettings.Default.IgnoreNullValues(true);
});
现在,如果我在Startup.ConfigureServices方法中保留对MapperConfig.Config的调用,则会出现错误“必须使用ServiceAdapter调用映射”。
不确定如何/在何处完成。
行tanentId
需要进入映射配置。
var tenantId = MapContext.Current.GetService<IConfiguration>().GetSection("MySettings").GetValue<int>("DefaultTenantId");
例如,
TypeAdapterConfig<CountyDetail, CountyVM>.NewConfig()
.Map(d => d.TanentId,
s => MapContext.Current.GetService<IConfiguration>().GetSection("MySettings").GetValue<int>("DefaultTenantId"));