How to publish a single dynamic service and utilize Generics

Posted Feb 12 2008, 05:40 PM by Arif.Budimartoyo  

If you want to provide a single - dynamic service and utilize the power of Generics, you probably will create the Generic method something like this;

public bool Update<T>(T updatedItem) {...}

And someday you'll probably need to publish this service to be able to participate in Serialization as well as Deserialize them (maybe through the WebService). You will need something like this below service to make similiar to the generic method in the serialization communication by passing the type as a parameter.

[WebMethod(MessageName = "Update", EnableSession = true)]
public bool Update(string entityType, string stringXml)
{
   ...
}

The type of entity might need to be passed as well as the serialized entity in xml through the service parameters.

You will then call the generic method which has been provided before. Nice, but the problem now is how to translate the entityType which is supplied as string to be T as a generic type in Update<T>?

By using the Reflection, you will now can utilize the MethodInfo and MakeGenericMethod to be invoked as a generic method. However you also need to deserialize the serialized object that was supplied as string xml before passing it in to the generic method.

MethodInfo serializerMethod = typeof(ObjectSerializer).GetMethod("DeserializeObject");
MethodInfo serializerMethodBound = serializerMethod.MakeGenericMethod(domainType);
object objDeserialized = serializerMethodBound.Invoke(null, new object[] { stringXml });
MethodInfo synchMethod = typeof(ISynchronization).GetMethod("Update");
MethodInfo synchMethodBound = synchMethod.MakeGenericMethod(domainType);
synchMethodBound.Invoke(m_UpdaterService, new object[] { objDeserialized }); //this is the same as you call the Update<T> method

The T will be supplied as Type in MakeGenericMethod. And you will now able to use generic method and publish it into serialize-deserialize communication environment.
This could be helpful when you want to provide a single and dynamic service to be used to transfer the unlimited type to the service provider using the power of generics.

Cheers,...

 

Share this post: | | | |

Comments

Wirawan said:

Wondering what brain do you have guru :D.

# February 25, 2008 10:13 AM