0

将 Mapster 与 Mapster DI 包一起使用,我还有一个名为 MapperConfig 的静态类,它有一个静态方法,可以将我的所有 dto 映射到视图模型。

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

不确定如何/在哪里完成..

4

1 回答 1

0

tenantId需要进入映射配置的线路。

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"));
于 2020-05-08T01:07:43.963 回答