简体   繁体   中英

Mapping Container<T> to T using AutoMapper

My question is very similar to the one asked here , but I was unable to find a solution based on the provided answers. I must be missing something that's right around the corner.

I have a custom converter that allows me to do the following:

cfg.CreateMap<Container<int>, int>().ConvertUsing(new ContainerConverter<Container<int>, int>());

But int being not the only type argument, is there a concise way to express:

cfg.CreateMap<Container<T>, T>().ConvertUsing(new ContainerConverter<Container<T>, T>());

Without having to do:

cfg.CreateMap<Container<int>, int>().ConvertUsing(new ContainerConverter<Container<int>, int>());
cfg.CreateMap<Container<long>, long>().ConvertUsing(new ContainerConverter<Container<long>, long>());
...

For every T in use?

In my situation, properties of Container<T> and T are in turn members of classes A1, A2... and B1, B2... . The mapping is performed by calling

B dest = mapper.Map<A, B>(source);

Thank you in advance.

If you don't mind the boxing, you can use a generic converter.

static void Main(string[] args)
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap(typeof(Container<>), typeof(object)).ConvertUsing(typeof(ContainerConverter<>));
    });
    config.AssertConfigurationIsValid();
    //config.BuildExecutionPlan(typeof(Destination), typeof(Source)).ToReadableString().Dump();
    var mapper = config.CreateMapper();
    mapper.Map<int>(new Container<int>{ Value = 12 }).Dump();
}
public class ContainerConverter<T> : ITypeConverter<Container<T>, object>
{
    public object Convert(Container<T> source, object destination, ResolutionContext c)
    {
        return source.Value;
    }
}
public class Container<T>
{
    public T Value { get; set; }
}

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