Saturday, November 14, 2009

Wrapping objects with interfaces

Have you ever had to map data to or from 3rd party components? Have you ever had to use reflection to access properties or methods you know the signature for on object you dont' have type for at compile time? This has happened a few times for me, especially when I have to deal with webservices defined by autogenerated classes.

My solution to this is to create an interface that resembles the objects I need to handle. I have made a small helper that will make proxy object for you that implements the provided interface and forwards all property calls and method calls to the object you need access to. This is how you can use it.

IMyInterface wrapped = anyObject.WrapAs<IMyInterface>();

Now you are able to create an interaction that can operate on your object. This might also be a way integrate with components you don't want a direct dependency on.

No comments:

Post a Comment