如何在ASP.NET Core中设置Automapper
我在.NET方面比较新,而且我决定解决.NET Core问题,而不是学习“老方法”。 我在这里find了一个关于设置AutoMapper for .NET Core的详细文章,但是对于新手来说,有没有更简单的漫游?
我想到了! 以下是详细信息:
- 通过NuGet将主要的AutoMapper软件包添加到您的解决scheme中。
- 通过NuGet将AutoMapperdependency injection包添加到您的解决scheme。
-
从
Startup.cs
调用AddAutoMapper()
扩展,如下所示。public void ConfigureServices(IServiceCollection services) { // .... Ignore code before this services.AddMvc(); // Already included. Add your code below this. services.AddAutoMapper(); // <-- This is the line you add. // services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature.
}
-
为映射configuration文件创build一个新类。 (我在名为
MappingProfile.cs
的主解决scheme目录中MappingProfile.cs
了一个类,并添加了以下代码)。我将使用User
和UserDto
对象作为示例。public class MappingProfile : Profile { public MappingProfile() { // Add as many of these lines as you need to map your objects CreateMap<User, UserDto>(); CreateMap<UserDto, User>(); } }
-
要在代码中调用映射对象,请执行以下操作:
public class UserController : Controller { // Create a field to store the mapper object private readonly IMapper _mapper; // Assign the object in the constructor for dependency injection public UserController(IMapper mapper) { _mapper = mapper; } public async Task<IActionResult> Edit(string id) { // Instantiate source object // (Get it from the database or whatever your code calls for) var user = await _context.Users .SingleOrDefaultAsync(u => u.Id == id); // Instantiate the mapped data transfer object // using the mapper you stored in the private field. // The type of the source object is the first type argument // and the type of the destination is the second. // Pass the source object you just instantiated above // as the argument to the _mapper.Map<>() method. var model = _mapper.Map<User, UserDto>(user); // .... Do whatever you want after that! } }
我希望这可以帮助开始使用ASP.NET Core的人! 我欢迎任何反馈或批评,因为我还是新来的.NET世界!
theutz'在这里的答案是非常好的,我只是想补充一点:
如果让映射configuration文件inheritanceMapperConfigurationExpression
而不是Profile
,那么可以非常简单地添加一个testing来validation映射设置,这总是很方便:
[Fact] public void MappingProfile_VerifyMappings() { var mappingProfile = new MappingProfile(); var config = new MapperConfiguration(mappingProfile); var mapper = new Mapper(config); (mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid(); }
我正在使用AutoMapper 6.1.1和asp.net Core 1.1.2。 首先定义Profile类由Automapperinheritance的Profile类。 我创build了一个空的IProfile接口,目的只是find这个类的类
public class UserProfile : Profile, IProfile { public UserProfile() { CreateMap<User, UserModel>(); CreateMap<UserModel, User>(); } } Now Create a seperate class eg Mappings public class Mappings { public static void RegisterMappings() { var all = Assembly .GetEntryAssembly() .GetReferencedAssemblies() .Select(Assembly.Load) .SelectMany(x => x.DefinedTypes) .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType())); foreach (var ti in all) { var t = ti.AsType(); if (t.Equals(typeof(IProfile))) { Mapper.Initialize(cfg => { cfg.AddProfiles(t); // Initialise each Profile classe }); } } } }
现在在Startup.cs文件中的MVC Core web Project中,在构造函数调用Mapping类中,它将在应用程序加载时初始化所有的映射
Mappings.RegisterMappings();
关于theutz答案,不需要在控制器构造函数中指定IMapper映射参数。
您可以使用Mapper,因为它是代码中任何位置的静态成员。
public class UserController : Controller { public someMethod() { Mapper.Map<User, UserDto>(user); } }