【问题标题】:Reading configuartion inside Automapper profile在 Automapper 配置文件中读取配置
【发布时间】:2018-01-03 04:12:13
【问题描述】:

我在一个 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 字符串,但我不知道如何将配置服务或值注入配置文件并同时使用程序集扫描。

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

【问题讨论】:

  • 您可以改用您的 DI 容器。
  • 怎么样?我将我的配置注册为服务,但如何将其注入映射配置文件?
  • 像往常一样,使用容器创建配置文件实例。
  • 是的,但这会注入控制器。如何使其注入映射配置文件?
  • 配置文件只是另一个对象。

标签: c# automapper


【解决方案1】:

扩展方法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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2017-09-22
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多