我在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字符串,但我无法弄清楚如何将配置服务或值注入配置文件并同时使用程序集扫描。
这是手动注册每个配置文件的唯一方法吗?
扩展方法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;
}
}