[英]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.