首先需要在NuGet中引用AutoMapper的类库
install-package AutoMapper install-package AutoMapper.Extensions.Microsoft.DependencyInjection
然后创建好要进行转换的类
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; } }
然后再创建一个标志接口IProfile
internal interface IProfile { }
接下来创建一个类来继承AutoMapper的Profile类与实现刚才创建的标志接口IProfile,并且在构造函数中配置关系映射
public class MyProfile: Profile,IProfile { public MyProfile() { CreateMap<User, UserDto>(); CreateMap<UserDto, User>(); } }
然后再创建一个类来注册关系映射
public class Mappings { public static void RegisterMappings() { //获取所有IProfile实现类 var allType = Assembly .GetEntryAssembly()//获取默认程序集 .GetReferencedAssemblies()//获取所有引用程序集 .Select(Assembly.Load) .SelectMany(y => y.DefinedTypes) .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType())); foreach (var typeInfo in allType) { var type = typeInfo.AsType(); if (type.Equals(typeof(IProfile))) { //注册映射 Mapper.Initialize(y => { y.AddProfiles(type); // Initialise each Profile classe }); } } } }
从上面代码可以看出使用标志接口来判断注册映射类进行注册映射,
最后只需在Startup类的ConfigureServices方法中添加服务和将Mappings添加到中间件即可使用
public void ConfigureServices(IServiceCollection services) { services.AddAutoMapper(); services.AddMvc(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { Mappings.RegisterMappings(); }
然后就可以使用automapper,
public class ValuesController : Controller { private IMapper _mapper { get; set; } public ValuesController([FromServices]IMapper mapper) { this._mapper = mapper; } // GET api/values [HttpGet] public UserDto Get() { User user = new User() { ID = 1, Name = "狗娃" }; var dto = Mapper.Map<User, UserDto>(user); return dto; }}
因为core使用DI创建对象,所以只需添加构造函数即可。
时间: 2024-10-15 01:25:50