繁体   English   中英

MVC Core 2.0服务中的Automapper.AddAutoMapper()行为

[英]Automapper in MVC Core 2.0 services.AddAutoMapper() behavior

我有这样的解决方案:

MVC Core 2.0 application <-> Business Class library <-> Domain class library
(ViewModel)    <- P1 ->      (Dto)         <-P2->       (Domain entity)

我在每个MVC和Business项目中创建了Automapper配置文件,用于映射ViewModel <-> Dto(P1)和Dto <-> Domain实体(P2)。 P1配置文件和地图在MVC项目中,P2配置文件和地图在业务库中。

然后,我创建了一个xUnit测试项目,该项目创建了一个Dto对象,并将其发送到业务服务,并在我称为init的单元测试中发送给它:

Business.App.AutoMapperConfiguration.Configure();

而且此单元测试的工作完全符合预期。

然后,我在MVC控制器中执行相同的操作(甚至从单元测试中复制/粘贴了代码),并且在将Dto映射到Domain实体时遇到错误:

Unmapped members were found. Review the types and members below...

我在startup.cs中配置了Automapper映射,如下所示:

services.AddAutoMapper();

如果我正确理解,应该遍历继承Profile的类的所有程序集并将它们添加到配置中。

示例图:

public class StrankaMap : Profile
{
    public override string ProfileName => nameof(StrankaMap);

    public StrankaMap()
    {
        CreateMap<SomeDto, SomeDomainEntity>().ReverseMap()
        CreateMap<AnotherDto, AnotherDomainEntity>().ReverseMap()
    }
}

我不知道如果我的单元测试有效但不是从MVC应用程序中导致此错误的原因-我什至将代码从单元测试复制到MVC控制器并运行。 我怀疑配置错误。 我是否正确假设在Startup.cs内添加services.AddAutoMapper(); 足以使其工作吗?

解决方案 (编辑)

显然我误解了service.AddAutoMapper()将遍历所有程序集并搜索Profile继承的类。 也许有更好的解决方案,但在@LucianBargaoanu评论的提示的帮助下,我使用了以下解决方案。

我这样解决了:

// Startup.cs

services.AddAutoMapper(
    typeof(Business.App.AutoMapperConfiguration),
    typeof(MvcApp.Infrastructure.Configuration.AutoMapperConfiguration));


//And the AutoMapperConfiguration class:

namespace MvcApp.Infrastructure.Configuration
{
    using AutoMapper;

    public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<Models.Mapping.StrankaMap>();
            });
        }
    }
}

显然我误解了service.AddAutoMapper()将遍历所有程序集并搜索Profile继承的类。 也许有更好的解决方案,但在@LucianBargaoanu评论的提示的帮助下,我使用了以下解决方案。

我这样解决了:

// Startup.cs

services.AddAutoMapper(
    typeof(Business.App.AutoMapperConfiguration),
    typeof(MvcApp.Infrastructure.Configuration.AutoMapperConfiguration));


//And the AutoMapperConfiguration class:

namespace MvcApp.Infrastructure.Configuration
{
    using AutoMapper;

    public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<Models.Mapping.StrankaMap>();
            });
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM