阅读Automapper配置文件中的配置

时间:2017-12-30 23:20:31

标签: c# automapper

我在asp.net core 2.0项目中使用Automapper。我使用自动装配扫描注册我的映射配置文件,如下所示:

services.AddAutoMapper();

我的数据层中有如下所示的映射配置文件:

public class JobDetailMappingProfile : Profile
{
    public JobDetailMappingProfile()
    {
        string dateFormat = "MM/dd/yyyy"; //todo: get this from main app config

        CreateMap<JobDetail, JobDetailViewModel>()
            .ForMember(x => x.StartDate, opt => opt.MapFrom(s => s.StartDate.ToString(dateFormat)))
            .ForMember(x => x.StartDate, opt => opt.MapFrom(s => s.StartDate.ToString(dateFormat)));

        CreateMap<JobDetailViewModel, JobDetail>()
            .ForMember(x => x.StartDate, opt => opt.MapFrom(s => DateTime.ParseExact(s.StartDate, dateFormat, CultureInfo.InvariantCulture )))
            .ForMember(x => x.EndDate, opt => opt.MapFrom(s => DateTime.ParseExact(s.EndDate, dateFormat, CultureInfo.InvariantCulture)));

    }
}

我想从项目设置文件中读取dateFormat字符串,但我无法弄清楚如何将配置服务或值注入配置文件并同时使用程序集扫描。

这是手动注册每个配置文件的唯一方法吗?

1 个答案:

答案 0 :(得分:0)

扩展方法AddAutoMapper()关于在其实现中添加配置文件所做的程序集扫描最终使用Activator.CreateInstance来创建配置文件的实例。你正在寻找的东西并不是现成的。但这是一种你可以自己写的扩展方法:

public static class AutoMapperExtension
{
    public static IServiceCollection AddAutoMapper(this IServiceCollection @this, IConfiguration configuration)
    {
        var assembliesToScan = AppDomain.CurrentDomain.GetAssemblies();
        var allTypes = assembliesToScan.Where(a => a.GetName().Name != "AutoMapper").SelectMany(a => a.DefinedTypes).ToArray();
        var profiles = allTypes.Where(t =>
        {
            if (typeof(Profile).GetTypeInfo().IsAssignableFrom(t))
                return !t.IsAbstract;
            return false;
        }).ToArray();

        Mapper.Initialize(expression =>
        {
            foreach (var type in profiles.Select(t => t.AsType()))
                expression.AddProfile((Profile)Activator.CreateInstance(type, configuration));
        });

        return @this;
    }
}