c# - 在映射时向 Automapper 提供构造函数参数

标签 c# dependency-injection automapper

我有一组我想用 Automapper 映射到的类。但是,每个类都有一个构造函数参数。此参数对于所有成员都是同一类型,但在我要进行映射之前我不知道要提供的值。

我找到了 ConstructUsing 方法,但这需要我在配置时指定参数值。我更愿意在映射时执行此操作,以避免需要为参数的每个实例创建单独的 MappingEngine。我找到了映射到已创建目标对象的 Map 重载。这很有用,但不适用于列表或对象图。

本质上,我正在寻找类似 Autofac 的 resolve 方法的东西,它只适用于 Automapper 的 Map 方法。

Resolve<IFoo>( new TypedParameter( typeof( IService ), m_service) );

最佳答案

通过阅读 Automapper 源代码,我找到了一个可行的解决方案,我在下面进行了描述。

首先,您需要指定要使用服务定位器进行构建。

IConfiguration configuration = ...;
configuration.CreateMap<Data.Entity.Address, Address>().ConstructUsingServiceLocator();

然后在调用 map 时,使用 opts 参数指定一个特定的服务定位器

// Use DI container or manually construct function
// that provides construction using the parameter value specified in question.
// 
// This implementation is somewhat Primitive, 
// but will work if parameter specified is always the only parameter
Func<Type, object> constructingFunction =
    type => return Activator.CreateInstance( type, new object[] { s_service } );

mappingEngine.Map<Data.Entity.Address, Address>(
    source, opts: options => options.ConstructServicesUsing( constructingFunction );

上面 constructingFunction 指示的“ServiceLocator”优先于提供给 IConfiguration.ConstructServicesUsing(...) 的函数

关于c# - 在映射时向 Automapper 提供构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13446599/

相关文章:

c# - 从字符串到 bool 值的奇怪映射行为

C# automapper 嵌套集合

c# - 带有 DataReader 的 AutoMapper DynamicMap 针对接口(interface)

c# - 我有一个 RichTextBox,里面装满了文本文件中的文本,我现在想将文本中包含单词 "Error"的所有地方都涂成红色,该怎么做?

c# - 依赖注入(inject)的 DbContext 始终为 null

dependency-injection - 如何使用 PARAMETER 构造函数注册类型?

java - Spring Bean(错误)配置

c# - 使用 map 坐标确定点是否在矩形中

c# - 转换为通用基类失败

c# - 接受返回 null 的方法 - C# .NET MVC