简体   繁体   English

在没有泛型的情况下配置AutoMapper

[英]Configuring AutoMapper without Generics

I am trying to configure AutoMapper without using generics as I want to configure it at runtime. 我想在不使用泛型的情况下配置AutoMapper,因为我想在运行时进行配置。

I want to configure the SubstiteNulls method and be able to do the equivalent of: 我想配置SubstiteNulls方法,并能够执行以下操作:

Mapper.CreateMap<Source, Dest>()
    .ForMember(dest => dest.Value, opt => opt.NullSubstitute("Other Value"));

But I can't figure out how to do this. 但是我不知道该怎么做。 You can pass they Type objects into the CreateMap factory method but when you use the ForMember method, the opt object does not contain the NullSubstitute method and I imagine this is due to the lack of generic that I am using here. 您可以将它们的Type对象传递给CreateMap工厂方法,但是当您使用ForMember方法时, opt对象不包含NullSubstitute方法,我想这是由于我在这里使用的泛型缺乏。

Any ideas on how I can achieve this? 关于如何实现此目标的任何想法?

Update 更新资料

These are the options that I am getting: 这些是我得到的选择:

在此处输入图片说明

Currently the NullSubstitute configuration is not available on the IMappingExpression interface which is used when you are using the non generic version of CreateMap . 当前,在使用非通用版本的CreateMap时,将在IMappingExpression接口上使用NullSubstitute配置。

There is no limitation which is preventing Automapper to have this method on the IMappingExpression so currently this is just not supported. 没有限制,可以阻止IMappingExpressionIMappingExpression上使用此方法,因此当前不支持此方法。

You have three options: 您有三种选择:

  • Create an issue on Github and wait until it is implemented 在Github上创建问题,并等待其实施
  • Fork the project and implement the method yourself. 分叉项目并自己实现方法。 It is very easy you can use the generic version as an example. 您可以使用通用版本作为示例非常容易。
  • Or if you want a quick but very dirty solution. 或者,如果您想要快速但非常肮脏的解决方案。 With reflection you can get the underlaying PropertyMap from the configuration and call the SetNullSubstitute method on it: 通过反射,您可以从配置中获取底层的PropertyMap并对其调用SetNullSubstitute方法:

     Mapper.CreateMap(typeof(Source), typeof(Dest)) .ForMember("Value", opt => { FieldInfo fieldInfo = opt.GetType().GetField("_propertyMap", BindingFlags.Instance | BindingFlags.NonPublic); var propertyMap = (PropertyMap) fieldInfo.GetValue(opt); propertyMap.SetNullSubstitute("Null Value"); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM