我需要在 ASP.NET Core
的 AutoMapper
配置文件类中使用服务层,但是当我在构造函数中注入(inject)服务时,它不起作用。例如:
public class UserProfile : Profile
{
private readonly IUserManager _userManager;
public UserProfile(IUserManager userManager)
{
_userManager = userManager;
CreateMap<User, UserViewModel>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
}
}
在Startup
类中:
public class Startup
{
public IConfigurationRoot Configuration { set; get; }
public Startup(IHostingEnvironment env)
{
//some code
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddMvc();
services.AddScoped<IUsersPhotoService, UsersPhotoService>();
services.AddAutoMapper(typeof(UserProfile));
}
}
如何做到这一点?
最佳答案
要解决您的问题,您只需在 DI 中连接 IUserManager
,并确保解决 UserProfile
依赖关系。
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSingleton<IUserManager, UserManager>();
services.AddSingleton(provider => new MapperConfiguration(cfg =>
{
cfg.AddProfile(new UserProfile(provider.GetService<IUserManager>()));
}).CreateMapper());
}
话虽如此,我可能会尝试保持每个类的单一责任,并且不将任何服务注入(inject)到映射配置文件中。您可以在映射之前填充对象。这样单元测试也可能更容易。
关于asp.net-core - 如何在 AutoMapper 配置文件类中注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877379/