Net 6环境下的.net core项目里如何使用AutoMapper实现依赖注入
注: AutoMapper 是一个对象-对象映射器,可以将一个对象映射到另一个对象。
一、在Nuget引入AutoMapper、AutoMapper.Extensions.DependencyInjection这两个NuGet包
二、定义RBACProfile类继承Profile
public class RBACProfile: Profile
{
public HongShiRBACProfile()
{
//配置文件 注意谁赋值给谁的顺序
CreateMap<AddUserDto, UserInfo>();
}
}
三、在Program.cs中注册我的的类
builder.Services.AddAutoMapper(typeof(HongShiRBACProfile));
四、在构造函数中注入:
public class HongShIController : ControllerBase
{
public HongShIController(IMapper mapper)
{
_mapper = mapper;
}
private readonly IMapper _mapper;
}
五、在方法中进行调用Map存储:
[HttpPost]
public IActionResult AddUser(AddUserDto userInfo)
{
var user = _mapper.Map<UserInfo>(userInfo);
var list = Users.Add(user);
return Ok(list);
}