简体   繁体   中英

Configuring AutoMapper without Generics

I am trying to configure AutoMapper without using generics as I want to configure it at runtime.

I want to configure the SubstiteNulls method and be able to do the equivalent of:

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.

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 .

There is no limitation which is preventing Automapper to have this method on the IMappingExpression so currently this is just not supported.

You have three options:

  • Create an issue on Github and wait until it is implemented
  • 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:

     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"); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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