gpt4 book ai didi

c# - 带有构造函数参数的自动映射对象

转载 作者:行者123 更新时间:2023-11-30 23:05:52 25 4
gpt4 key购买 nike

我正在尝试将 AutoMapper 配置为使用需要构造函数参数的类。我对此进行了大量在线研究,并找到了几个示例...但它们要么不使用基于实例的 AutoMapper,要么适用于旧版本的 AutoMapper。

我正在使用 AutoMapper 深度克隆对象。这是我创建的个人资料:

public class ScannerAutoMapProfile : Profile
{
public ScannerAutoMapProfile()
{
CreateMap<AzureConfiguration>();
CreateMap<CommunityUser>();
CreateMap<Community>();
CreateMap<Contact>();
CreateMap<DatabaseConnection>();
CreateMap<DatabaseConfiguration>();
CreateMap<LoginManagement>();
CreateMap<MaxLoadSeconds>();
CreateMap<ScanTime>();
CreateMap<ScanningAcceleration>();
CreateMap<ScanningWindow>();
CreateMap<ScanningInterval>();
CreateMap<Scanning>();
CreateMap<SearchParameterUser>();
CreateMap<SearchParameter>();
CreateMap<ScannerConfiguration>();
}

private void CreateMap<TModel>()
{
CreateMap<TModel, TModel>();
}
}

问题出现在 ScannerConfiguration 中,它采用单个字符串参数。

这是我正在使用的 Autofac 模块:

public class AutoMapperModule : Module
{
protected override void Load( ContainerBuilder builder )
{
base.Load( builder );

var assemblies = AppDomain.CurrentDomain.GetAssemblies();

builder.RegisterAssemblyTypes( assemblies )
.Where( t => typeof(Profile).IsAssignableFrom( t ) && !t.IsAbstract && t.IsPublic )
.As<Profile>();

builder.Register( c => new MapperConfiguration( cfg =>
{
foreach( var profile in c.Resolve<IEnumerable<Profile>>() )
{
cfg.AddProfile( profile );
}
} ) )
.AsSelf()
.SingleInstance();

builder.Register( c => c.Resolve<MapperConfiguration>().CreateMapper( c.Resolve ) )
.As<IMapper>()
.SingleInstance();
}
}

(为此感谢 http://www.protomatter.co.uk/blog/development/2017/02/modular-automapper-registrations-with-autofac/)。

我可以成功地实例化一个 IMapper,这表明 Autofac 的东西工作正常。但是当我尝试调用 map 时:

_onDisk = Mapper.Map<ScannerConfiguration>( _inMemory );

它因“ScannerConfiguration 没有无参数构造函数”异常而失败。

不幸的是,虽然我很确定我需要为 Map() 调用提供一些选项,但我一直无法弄清楚如何去做。我需要传递给构造函数的参数是 ScannerConfiguration 的公共(public)属性,称为 SourceFilePath。

最佳答案

既然ScannerConfiguration需要一个参数,为什么不自己初始化呢?

var sc = new ScannerConfiguration("some string value");
_onDisk = Mapper.Map( _inMemory, sc );

关于c# - 带有构造函数参数的自动映射对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48551619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com