簡體   English   中英

如何跨Visual Studio項目初始化自動映射器

[英]how to initialize automapper accross Visual Studio Projects

我在Visual Studio ASP.NET MVC應用程序的多個dll項目中使用了自動映射器。 我在主WebUI項目的Application_Start()方法中調用的每個項目中創建了一個AutoMapperConfiguration類。

問題是我試圖以相同的方式為Visual Studio解決方案的每個單獨項目初始化自動映射器,但我收到一條錯誤消息,說自動映射器只能被初始化一次。

如果僅對一個ddl項目執行此操作,而對多個dll項目不執行此操作,則初始化自動映射程序的方式將起作用,並且在自動映射程序的版本8.1.1中,我還會收到一條警告,指出Mapper.Initialize方法已棄用。 在9.0.0版中,不再存在initialize方法...

我怎樣才能做到這一點?

謝謝你的幫助,

E.

我在每個dll項目中都有以下代碼:

public class AutoMapperConfiguration
    {
        public static void ConfigureAutoMapper()
        {
            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile<BusinessToDomainProfile>();
                cfg.AddProfile<DomainToBusinessProfile>();
            });
        }
    }

我在Global.asax Appplication_Start方法中將其稱為我的主要WebUI項目:

   Domain.Mappers.AutoMapperConfiguration.ConfigureAutoMapper(); 
   Business.Mappers.AutoMapperConfiguration.ConfigureAutoMapper(); 

將您的Profile類放在不同的項目中,並在ASP.NET MVC項目中初始化一次AutoMapper。

// Load all profiles in an assembly by specifying a type from the assembly
Mapper.Initialize(cfg => {
    cfg.AddProfiles(typeof(Student), typeof(Course));
});

不要在任何類庫項目(dll)中調用Mapper.Initialize。 可執行文件(Web應用程序,控制台應用程序等)負責初始化。

您只能初始化一次映射器。 通常,您在“設置為啟動項目”中進行初始化,因此,在這種情況下,請收集所有這些cfg.AddProfile()並將其放入您的global.asax.cs Application_Start Initialize()調用中。

我正在使用Global.asax.cs Application_Start()方法來處理較舊的應用程序,該方法可從一系列項目中配置AutoMapper配置文件,如下所示:

Mapper.AddProfile<AutoMapperConfigurationApi>();
Mapper.AddProfile<AutoMapperConfiguration>();
Mapper.AddProfile<AutoMapperWebConfiguration>();

其中每個配置文件(例如AutoMapperConfigurationApi)是不同項目中的獨立配置類:

namespace API_MVC
{
    public class AutoMapperConfigurationApi : Profile
    {
        protected override void Configure()
        {
            CreateMap<EnquiryCreateRequest, EnquiryDto>();

        }
    }
}

我也有一個只有.NET Core 3的應用程序,而且我使用的是:

在我的Startup.cs MVC項目中:

public void ConfigureServices(IServiceCollection services)
{
     ...

     services.AddAutoMapper(new Assembly[] {
              typeof(SomeProject.AutoMapperProfile).Assembly,
              typeof(SomeOtherProject.AutoMapperProfile).Assembly
            });
     ...
}

通過設置AutoMapperProfile.cs文件,如下所示:

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<MyModel, MyModelDto>();
    }
}

我在控制器中為Mapper使用依賴注入,例如:

public MyController
{
    public MyController(IMapper mapper)
    {

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM