【问题标题】:Maping generic interface to concreate class but using interface definition -> automapper将通用接口映射到具体类但使用接口定义-> automapper
【发布时间】:2018-06-27 17:13:53
【问题描述】:

嘿,我正在尝试将我的泛型类映射到具体类,但使用它的接口。

我的服务返回给我的数据类型是

IPaggedResults

我希望能够将其映射到

IPaggedResults

如果我调用映射,它会起作用:

_mapper.Map>

但我想使用以下语法:

_mapper.Map>

public class PaggedResults<T> : IPaggedResults<T>
{
    public IEnumerable<T> Results { get; protected set; }
    public int TotalResults { get; protected set; }
    public int TotalPages { get; protected set; }
    public int ResultsPerPage { get; protected set; }

    public PaggedResults(IEnumerable<T> results, int totalResults, int resultsPerPage)
    {
        Results = results;
        TotalResults = totalResults;
        TotalPages = totalResults / resultsPerPage;
        ResultsPerPage = resultsPerPage;
    }
}


public class CustomerDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string NIP { get; set; }
}

我的映射器配置:

        public static IMapper Initialize()
            => new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<CustomerCompany, CustomerDto>();
                cfg.CreateMap(typeof(IPaggedResults<>), typeof(PaggedResults<>));
                cfg.CreateMap(typeof(IPaggedResults<>), typeof(IPaggedResults<>)).As(typeof(PaggedResults<>));
            }).CreateMapper();

我正在使用 Jimmy Bogard 的 Automapper。

【问题讨论】:

  • 什么是_mapper ???
  • 我忘了 - _mapper 是 IMapper 实例
  • 但是IMapper 是什么,它是你创建的一个类,对吧?放代码
  • IMapper 是来自 Automapper 库的 Automapper 实例。我把mapper配置放在上面。

标签: c# automapper


【解决方案1】:

我可以通过以下代码实现:

IMapperConfigurationExpression创建一个扩展

public static class IMapperConfigurationExpressionExtensions 
{
    public static void MapPaggedResults<TSource, TDestination>(this IMapperConfigurationExpression exp){
        exp.CreateMap(typeof(PaggedResults<TSource>), typeof(IPaggedResults<TDestination>))
       .ConstructUsing((source, ctx) => { return ctx.Mapper.Map<PaggedResults<TDestination>>(source) as IPaggedResults<TDestination>; });
    }
}

然后使用这个配置:

public static IMapper Initialize()
=> new MapperConfiguration(cfg =>
{
   cfg.CreateMap(typeof(IPaggedResults<>), typeof(PaggedResults<>));
   cfg.MapPaggedResults<CustomerCompany, CustomerDto>();
}).CreateMapper();

那么两个结果都可以得到:

var _mapper = Initialize();
IPaggedResults<CustomerCompany> source = new PaggedResults<CustomerCompany>(
    new List<CustomerCompany>() { new CustomerCompany() {Id =42, Name = "SomeName", NIP = "someNIP" } }, 1, 1);
var resut = _mapper.Map<PaggedResults<CustomerDto>>(source);
var resut2 = _mapper.Map<IPaggedResults<CustomerDto>>(source);

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 2022-08-19
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2011-07-31
    相关资源
    最近更新 更多