views:

69

answers:

2

I have two classes:

public class TestClass1
{
    public int TestInt { get; set; }

    public void TestMethod()
    {
        // Do something
    }
}

public class TestClass2
{
    public int TestInt { get; set; }

    public void TestMethod()
    {
        // Do something
    }
}

I want to create interface that I can use for both classes. The easiest solution is to implement the interface on TestClass1 and TestClass2 but I don;t have access to the implementation of these classes (external dll). I was wondering if I can create new interface and use AutoMapper to map TestClass1 and TestClass2 to ITestInterface:

public interface ITestInterface
{
    int TestInt { get; set; }

    void TestMethod();
}
+1  A: 

You say you require mapping "TestClass1 and TestClass2 to ITestInterface", however you'd need an instance of a class to map to as you can't create an instance of an interface.

I assume you're trying to treat the classes interchangeably by converting them to the same interface. If so Automapper isn't what you should be looking at - see this question on stack-overflow for some details on how to manage treating the classes as if they both implement the same interface (even if you don't have access to the source code).

saret
Thanks, it kind of solve my problem.
Woj
A: 

You can't map to a method as the target, only the source (using a custom projection):

Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.SomeValue, 
        opt => opt.MapFrom(src => src.GetSomeValue()))

But there's absolutely no way you can "map" a void method to another void method. It doesn't really make sense; mapping involves reading from one place and writing to another, and you can't "read" a value from a void method.

Aaronaught
You are right I can not map void to void value but I'm not interested in return value. I would like to map exectution of the method. Something like: Mapper.CreateMap<Source, Destination> .ForMember(dest => dest.DoSomething(), opt => opt.MapFrom(src => src.DoSomething()).
Woj
@Woj: Then you're not talking about mapping at all, you're talking about a wrapper or adapter: http://en.wikipedia.org/wiki/Adapter_pattern. Only *data* can be *mapped*.
Aaronaught