I'm looking for a way to accomplish the behavior illustrated in source code below. I've create WCF service proxies with the "Always generate message contracts" option. All of my request and response message contracts implement a common interface and I'd like to execute them using the same function. It seems to me that there should be a generic way to send messages through the client proxy, but I can't find it anywhere. Any help would be greatly appreciated!
// I can do this
private IPagedResponse GetAllFoods()
{
NutrientDBClient client = new NutrientDBClient();
GetAllFoodsRequest request = new GetAllFoodsRequest();
GetAllFoodsResponse response = client.GetAllFoods(request);
return response;
}
// I'd like to do this
private IPagedResponse ExecutePagedRequest(IPagedRequest request)
{
NutrientDBClient client = new NutrientDBClient();
IPagedResponse response = (IPagedResponse)client.Execute(request);
return response;
}
I've currently added an ExecutePagedRequest(IPagedRequest) method to NutrientDBClient and manually execute the correct service operation based on the concrete type of IPagedRequest. I'm looking for a more elegant way so that I can simply implement IPagedRequest on a message contract and it auto-magically works.
Below is how I solved this problem. My message contracts, implement IPagedRequest & IPagedResponse. NutrientDBClient is my code-generated client proxy (ClientBase). ExecutePagedRequest() does the message routing based on the concrete type of request.
public interface IPagedRequest
{
PagingContext PageInfoState { get; set; }
}
public interface IPagedResponse
{
PagingContext PageInfoState { get; }
IEnumerable ResultItems { get; }
}
public partial class NutrientDBClient : IHasPagedServiceOperations
{
public IPagedResponse ExecutePagedRequest(IPagedRequest request)
{
if (request == null) { throw new ArgumentNullException("request"); }
if (typeof(GetAllFoodsRequest).IsAssignableFrom(request.GetType()))
{
return GetAllFoods((GetAllFoodsRequest)request);
}
// Other Service Operations that take IPagedRequest and
// return IPagedResponse removed for example
throw new NotSupportedException(
string.Format("Paged requests of type {0} are not supported.",
request.GetType().Name));
}
}