【问题标题】:Create AutoMapper in Test Project (including AutoMapper.Profile classes)在测试项目中创建 AutoMapper(包括 AutoMapper.Profile 类)
【发布时间】:2019-12-20 14:01:46
【问题描述】:

我有一个使用 AutoMapper 的 .net 核心服务 API,在 Startup::ConfigureServices 中,服务集合使用 AddAutoMapper 扩展来执行 IMapper 接口的依赖注入所需的所有初始化,例如services.AddAutoMapper(typeof(Startup));我理解的方式是,通过这样做,对任何/所有 AutoMapper.Profile 类型进行扫描,以便将 DI 的 IMapper 设置到其他构造函数中。效果很好。

现在我正在为服务编写测试,想知道如何在 Startup 之外创建这个 IMapper?嘲笑它似乎没有意义,我只是想使用它,那么如何创建一个我需要的实例,利用我设置的所有 AutoMapper.Profiles?

【问题讨论】:

  • 您也可以在测试中使用AddAutoMapper。毕竟你想尽可能接近真实的东西。

标签: automapper


【解决方案1】:

我可以通过简单地创建一个指向所需 Profile 类的 MapperConfiguration 来完成这项工作:

var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile<TestProfile>());
IMapper _mapper = new Mapper(mapperConfig);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2016-09-06
    • 2012-09-11
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多