tags:

views:

31

answers:

1

I am trying to create an Interface-based Request/Response pattern for Web API requests to allow for asynchronous consumer/producer processing, but not sure how I would know what the underlying IResponse class is.

public void Run()
{
   List<IRequest> requests = new List<IRequest>();
   List<IResponse> responses = new List<IResponse();
   requests.Add(AmazonWebRequest); //should be object, trying to keep it simple
   requests.Add(EBayWebRequest);  //should be object, trying to keep it simple

   foreach (IRequest req in requests)
   {
      responses.Add(req.GetResponse());
   }

   foreach (IResponse resp in response)
   {
      typeof resp????
   }
}

interface IRequest
{
   IResponse GetResponse();
}

interface IResponse
{
}

public class AmazonWebServiceRequest : IRequest
{
   public AmazonWebServiceRequest()
   {
      //get data;
   }

   public IResponse GetResponse()
   {
      AmazonWebServiceRequest request = new AmazonWebServiceRequest();
      return (IResponse)request;
   }
}

public class AmazonWebServiceResponse : IResponse
{
   XmlDocument _xml;
   public AmazonWebServiceResponse(XmlDocument xml)
   {
      _xml = xml;
      _parseXml();
   }

   private void _parseXml()
   {
      //parse Xml into object;
   }
}

public class EBayWebRequest : IRequest
{
   public EBayWebRequest ()
   {
      //get data;
   }

   public IResponse GetResponse()
   {
      EBayWebRequest request = new EBayWebRequest();
      return (IResponse)request;
   }
}

public class EBayWebResponse : IResponse
{
   XmlDocument _xml;
   public EBayWebResponse(XmlDocument xml)
   {
      _xml = xml;
      _parseXml();
   }

   private void _parseXml()
   {
      //parse Xml into object;
   }
}
+1  A: 

You can check the type like this:

if (resp.GetType() == typeof(AmazonWebRequest))
{
// do something
}
else if (resp.GetType() == typeof(EBayWebRequest))
{
// do something
}

This can get messy though, it's better if you add a generic method on the interface to call for any implemented type, like

resp.Process();

Then handle the processing of the request inside each implementation of IResponse.

Jeff Schumacher
The resp.Process() is a good idea.
traderde