使用Mapster w / DI,我应该在哪里放置地图?

问题描述 投票:0回答:1

将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调用映射”。

不确定如何/在何处完成。

dependency-injection asp.net-core-3.1 mapster
1个回答
0
投票

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"));
© www.soinside.com 2019 - 2024. All rights reserved.