加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – 如何在AutoMapper配置文件类中注入服务

发布时间:2020-12-16 03:42:42 所属栏目:asp.Net 来源:网络整理
导读:我需要在ASP.NET Core中的AutoMapper配置文件类中使用服务层,但是当我在构造函数中注入服务时它不起作用.例如: public class UserProfile : Profile{ private readonly IUserManager _userManager; public UserProfile(IUserManager userManager) { _userMa
我需要在ASP.NET Core中的AutoMapper配置文件类中使用服务层,但是当我在构造函数中注入服务时它不起作用.例如:

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}"));
    }
}

在启动类中:

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());
}

说到这一点,我可能会尝试保持每个类的单一责任,而不是将任何服务注入到映射配置文件中.您可以在映射之前填充对象.这样,单元测试也可能更容易.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读