c# - 如何跨 Visual Studio 项目初始化自动映射器

标签 c# asp.net-mvc automapper

我在我的 Visual Studio ASP.NET MVC 应用程序的多个 dll 项目中使用 automapper。我在我的主 WebUI 项目的 Application_Start() 方法中调用的每个项目中都创建了一个 AutoMapperConfiguration 类。

问题是我正在尝试以相同的方式为我的 Visual Studio 解决方案的每个单独项目初始化自动映射器,但我收到一条错误消息,指出自动映射器只能初始化一次...

如果我只为一个 ddl 项目而不是为多个 dll 项目执行初始化 automapper 的方式,我还会收到一条警告,在 8.1.1 版的 automapper 中指出 Mapper.Initialize 方法已弃用.在 9.0.0 版本中,初始化方法不再存在...

我怎样才能做到这一点?

谢谢你的帮助,

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(); 

最佳答案

将您的配置文件类放在不同的项目中,并在您的 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 应用程序、控制台应用程序等)负责初始化。

关于c# - 如何跨 Visual Studio 项目初始化自动映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57464735/

相关文章:

c# - 获取区域设置 WinRT

c# - 是否可以在 C# 中扩展 'using' block ?

c# - 在我的 .Net Core 2.0 项目中,使用 .Net FW 包代替 .Net Standard(警告 NU1701)

list - 使用 AutoMapper 对特定属性进行自定义转换

asp.net-mvc - ViewModel 与域实体

c# - C# 日期时间和 SQL 日期时间之间的相等性比较失败

c# - 如果身份角色不是管理员,则从 Web Api 重定向到 MVC Controller

javascript - SweetAlert 使用@Html.ActionLink 确认提示

c# - 如何在 Asp.net core mvc 的 Controller 中获取自己的用户

asp.net-mvc-3 - 不在表单上时 MVC3 数据在发布时丢失?