Writing a bit of code that deals with a Response and a Request. Both can be in the form of XML, and both can be in the form of a C# Object created through a transform and serialization. (this is .NET 2.0)
Response and Request are base implementations of larger message types. Right now I have GetEligibility and FindCandidates.
Example of the Model.MessageModel classes used below:
public partial class GetEligibilityResponseMessage : ResponseMessage
public partial class ResponseMessage : Message
Because I won’t want to duplicate my mapping functionality I’ve decided to use generics to simplify the process, and it’s working out great:
Base Class Code
public virtual Model.MessageModel.Message MapToModel<T>(XmlDocument xml)
{
V3Mapper mapper = new V3Mapper();
Model.MessageModel.Message message = mapper.MapToDomainModel<T>(xml, Environment) as Model.MessageModel.Message;
return message;
}
public virtual XmlDocument MapToXml<T>(Model.MessageModel.Message message)
{
V3Mapper mapper = new V3Mapper();
XmlDocument xml= mapper.MapToV3Message<T>(message, Environment);
return xml;
}
When my code is first called, it has an XML document. I know this document will be mapped as a request, and so I call a virtual method that is overriden (and I think it’s ugly). The reason to keep the mapping code in the base is to not duplicate code, yet I find I am doing the exact thing I want to avoid by the following:
GetEligibility : BaseClass
public override Model.MessageModel.Message MapToModel<T>(XmlDocument xml)
{
if(typeof(T).IsAssignableFrom(typeof(GetEligibilityResponseMessage)))
{
return base.MapToModel<GetEligibilityResponseMessage>(xml);
}
else if (typeof(T).IsAssignableFrom(typeof(GetEligibilityRequestMessage)))
{
return base.MapToModel<GetEligibilityRequestMessage>(xml);
}
return null;//because this is a quick code snippet
}
Is there a more elegant way of doing this? I always know if I’m working with a Response or Request. I want to leave the functionality open so it’s not too tightly-coupled, but at the same time have it functional and fast.
This will be implemented by a number of different message types, and I really hate copy/paste style of coding, so an elegant solution would be great, but I’m not sure if there is one. (.NET 2.0)
You can use the MethodInfo.MakeGenericMethod Method to avoid having to check types before calling your generic method. Below is a quick usage example:
Notice that I used typeof(DateTime), but in your case you can replace that by typeof(T) to achieve the desired loosely-coupled solution.