.NET Core 应用程序中如何安装和使用数据实体对象映射工具AutoMapper?
2 个回答
-
在.NET Core的应用程序编程开发中,要安装和使用
AutoMapper
实体对象映射工具,首先需要通过Nuget包管理工具安装AutoMapper
以及依赖注入扩展包AutoMapper.Extensions.Microsoft.DependencyInjection
,然后调用services.AddAutoMapper()
方法完成服务注册,如:var services = new ServiceCollection(); services.AddAutoMapper(mapperConfig => mapperConfig.AddProfiles(GetType().Assembly)) // ...
-
这里提供一个简单的、完整的
AutoMapper
使用示例。首先,分别创建两个实体类
User
和UserDTO
:public class User { public int Id { get; set; } public string Name { get; set; } } public class UserDTO { public int Id { get; set; } public string Name { get; set; } }
再创建一个完成
AutoMapper
映射关系配置的接口ICustomMapper
及其对应的实现,如下:public interface ICustomMapper<T> { T MapUserToUserDTO(); } public class CustomMapper : ICustomMapper<UserDTO> { private readonly IMapper mapper; public CustomMapper(IMapper mapper) => this.mapper = mapper; public UserDTO MapUserToUserDTO() { User user = new User() { Id = 5, Name = "Iman" }; UserDTO userDTO = mapper.Map<UserDTO>(user); return userDTO; } }
最后,调用
ServiceCollection.AddAutoMapper()
方法完成服务注册,如下:using AutoMapper; using Microsoft.Extensions.DependencyInjection; namespace AutoMapperProject { class Program { private static IServiceProvider _serviceProvider; static void Main(string[] args) { RegisterServices(); ICustomMapper<UserDTO> service = _serviceProvider.GetService<ICustomMapper<UserDTO>>(); UserDTO userDTO = service.MapUserToUserDTO(); DisposeServices(); Console.WriteLine("Hello AutoMapper!"); } private static void RegisterServices() { var collection = new ServiceCollection(); collection.AddAutoMapper(typeof(Program)); collection.AddScoped<ICustomMapper<UserDTO>, CustomMapper>(); // ... _serviceProvider = collection.BuildServiceProvider(); } private static void DisposeServices() { if (_serviceProvider == null) { return; } if (_serviceProvider is IDisposable) { ((IDisposable)_serviceProvider).Dispose(); } } } }