【问题标题】:Using Mapster w/DI where should I be putting my mapping?使用带有 DI 的 Mapster 我应该把我的映射放在哪里?
【发布时间】:2022-02-14 22:54:28
【问题描述】:

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

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

【问题讨论】:

    标签: dependency-injection asp.net-core-3.1 mapster


    【解决方案1】:

    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"));
    

    【讨论】:

      猜你喜欢
      • 2014-03-04
      • 2020-09-30
      • 2019-07-11
      • 1970-01-01
      • 2016-08-25
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多