且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core MVC中的AutoMapper实现

更新时间:2023-02-16 09:35:44

确定.这里有几件事.您的AutoMapper配置,最简单的配置方法是:

OK. A few things here. Your AutoMapper config, the easiest way to build this is just:

services.AddAutoMapper(typeof(Startup));

这将从Startup类的程序集中扫描Profiles,并使用Mapper.Initialize自动添加它们.请勿致电Mapper.此后初始化.

That scans the assembly from the Startup class for Profiles, and automatically adds them using Mapper.Initialize. DO NOT call Mapper.Initialize after this.

接下来,您的个人资料.您正在做很多不应该做的事情.首先,您的个人资料正在调用AssertConfigurationIsValid-不会.接下来,它正在检查现有的TypeMap-不用.只需调用基本的CreateMap方法即可.

Next, your profile. You're doing a lot of things you shouldn't. First, your profile is calling AssertConfigurationIsValid - don't. Next, it's checking for existing TypeMaps - don't. Just call the base CreateMap method, that's it.

最后,您还有一个额外的AddAutoMapperClasses调用.不要使用它.摆脱它.您只需要"services.AddAutoMapper". AddAutoMapper方法使用传入的程序集中的Profile类调用Mapper.Initialize.

Finally, you've got an extra AddAutoMapperClasses call. Don't use that. Get rid of it. You just need the "services.AddAutoMapper". The AddAutoMapper method calls Mapper.Initialize, with the Profile classes found in the assembly you've passed in.