AutoMapper: Mapping objects with interface propert

2019-07-04 03:17发布

my current task needs to pay attention on mapping between different object types and so I recognized the very nice AutoMapper library.

So far easy to handle but these different objects contains complex interface type properties. Let me show you a code snippet:

public inferface IInterface
{
    string TextProperty { get; set;}
}

public class A : IInterface
{
    string TextProperty { get; set; }
}

public class B : IInterface
{
    string TextProperty { get; set; }
}


public inferface IComplexInterface
{
    IInterface ComplexProperty { get; set; }
}

public class ComplexA : IComplexInterface
{
    IInterface ComplexProperty { get; set; }
}

public class ComplexB : IComplexInterface
{
    IInterface ComplexProperty { get; set; }
}

In my case it is possible that class A is mapped to class B and vice versa.
Mapping from type A to B is no problem by configuring CreateMap<A, B>();
Mapping from class ComplexA to class ComplexB throws an exception:

Error mapping types.

Mapping types:

  • ComplexA -> ComplexB
  • NamespaceOfComplexA.ComplexA -> NamespaceOfComplexB.ComplexB

Type Map configuration:

  • ComplexA -> ComplexB
  • NamespaceOfComplexA.ComplexA -> NamespaceOfComplexB.ComplexB

Property:

  • ComplexProperty

A possible solution I already found here on stackoverflow could be a configuration as follows:

CreateMap<A, IInterface>().As<B>();
CreateMap<B, IInterface>().As<A>();

But in my case it is not working.

Any suggestions?

1条回答
ら.Afraid
2楼-- · 2019-07-04 04:11

Now, I found a solution that works for me.

I use AutoMapper with a non generic approach and so I configure via:

CreateMap(typeof(ComplexA), typeof(ComplexB))

To consider properties with complex types like interfaces or even abstract classes it is possible to write an own ValueResolver that has to implement the interface:

IValueResolver<object, object, object>

with following method:

public object Resolve(object source, object destination, object destMember, ResolutionContext context)
{
//...
}

To resolve interface/abstract class properties you can configure your types by enhancing the configuration with the method ForMember(...) and define a conrete ValueResolver for the particular property as follows:

CreateMap(typeof(ComplexA), typeof(ComplexB)).ForMember("ComplexProperty", x => x.ResolveUsing(new ValueResolver(/*...*/)));

In my case it was the solution to map the interface property to a concrete implementation of my class definitions.

Hope it is useful.

查看更多
登录 后发表回答