2017-08-11 124 views
-1

我使用AutoMapper的ASP.net核心。为了让DI运行,我用的是AutoMapper.Extensions.Microsoft.DependencyInjection的NuGet封装,让AutoMapper通过通过Asp.Net核心添加AutoMapper核心依赖注入并注入配置文件

private static void InitializeAutoMapper(IServiceCollection services) 
    { 
     services.AddAutoMapper(); 
    } 

这正常注册的配置文件,但是对于一些配置文件,我想也注入一些依赖于它们,例如:

public class IndividualDtoProfile : Profile 
{ 
    private readonly IIndividualFactory _individualFactory; 
    private readonly IMapper _mapper; 

    public IndividualDtoProfile(IIndividualFactory individualFactory, IMapper mapper) 
    { 
     _individualFactory = individualFactory; 
     _mapper = mapper; 
    } 

    public IndividualDtoProfile() 
    { 
     CreateMap<Individual, IndividualDto>(); 

     CreateMap<IndividualDto, Individual>() 
      .ConstructUsing(
       dto => 
       { 
        var gender = _mapper.Map<IndividualGender>(dto.Gender); 
        return _individualFactory.CreateIndividual(dto.FirstName, dto.LastName, gender, dto.BirthDate); 
       }); 
    } 
} 

唯一相关的讨论,我发现在这里:https://groups.google.com/forum/#!topic/automapper-users/5XK7pqGu_Tg

还几乎似乎暗示不使用的现有可能性善良,但手动映射简介秒。我唯一能看到的另一种可能是提供一个静态的ServiceProvider-Singleton,这看起来不太吸引人。

是否有可能将Auto.Net与ASP.Net Core一起使用,并让依赖注入到Profiles中?

编辑:由于评论,可能我也是一些根本错误:我正在学习域驱动设计,我有一个应用程序层。我想将从Web服务中使用的DTO映射回域实体,并且我认为,在那里使用工厂也是有意义的,否则我会绕过工厂中的逻辑。

+0

在这里添加DI真的有意义吗?最后,它只是将一个对象映射到另一个对象。如果你有测试,你也需要测试/模拟映射。从我的角度来看,双重工作。 – Artiom

+0

hm?我不明白你的观点:我想用AutoMapper进行一般映射,但对于某些地图,我希望使用工厂以保证一些不变量并确保每个对象都是为其特定工厂创建的。 –

+0

为什么你要在配置文件中使用/注入'IMapper'?配置文件用于在映射器准备使用之前添加注册(即通过Mapper.AssertConfigurationIsValid()执行验证)。虽然我通常更喜欢在任何地方注入IMapper,但是有一些限制。你在使用Automapper的EF预测吗?由于'.ProjectTo()'方法使用静态的'Mapper'类代替 – Tseng

回答

1

这是不支持开箱即用的设计。如果你想要它,你必须使用你的DI容器自己做。这已经被讨论过很多次了。例如,here。该docs

+0

谢谢,然后寻找另一个solutuon。 –

相关问题