簡體   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