vos*_*d01 3 c# dependency-injection automapper
我有一组我想用Automapper映射的类.但是,每个类都有一个构造函数参数.这个参数对于所有成员都是相同的类型,但是在我想要进行映射之前,我不知道要提供的值.
我找到了ConstructUsing
方法,但这需要我在配置时指定参数值.我宁愿在映射时执行此操作,以避免需要为MappingEngine
参数的每个实例创建单独的.我找到了Map
映射到已创建的目标对象的重载.这很有用,但它不适用于列表或对象图.
基本上,我正在寻找像Autofac这样的解决方法,只适用于Automapper的Map
方法.
Resolve<IFoo>( new TypedParameter( typeof( IService ), m_service) );
Run Code Online (Sandbox Code Playgroud)
通过Automapper源代码阅读,我找到了一个可行的解决方案,我将在下面介绍.
首先,您需要指定要使用服务定位器进行构建.
IConfiguration configuration = ...;
configuration.CreateMap<Data.Entity.Address, Address>().ConstructUsingServiceLocator();
Run Code Online (Sandbox Code Playgroud)
然后在调用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 );
Run Code Online (Sandbox Code Playgroud)
constructingFunction
上面指出的"ServiceLocator" 优先于提供的功能IConfiguration.ConstructServicesUsing(...)
归档时间: |
|
查看次数: |
3573 次 |
最近记录: |