我将数据提交给我偶尔会失去联系的网络服务(我国的互联网并不是很好)。
Web服务具有主端点和故障转移端点。
我主要通过复制与Web服务交互的代码来处理连接错误。与我合作的价值观真的很重要,为了让这个例子尽可能简单,我已经删除了很多复杂性。
private bool _testing = true;
protected async void GetPatient_Click(object sender, EventArgs e)
{
if (_testing)
{
await SendTestRequestToWebService(foo, bar);
}
}
private async Task SendTestRequestToWebService(string foo, string bar)
{
try
{
using (var client = Service.ServiceGatewayClient())
{
// Do stuff on the service.
var response = client.Operation(foo, bar);
ParseServiceResponse(response);
}
}
catch (System.ServiceModel.EndpointNotFoundException ex)
{
// Couldn't connect to the service, failover to the backup.
using (var client = ServiceFailover.ServiceGatewayClient())
{
// Do stuff on the service.
var response = client.Operation(foo, bar);
ParseFailoverServiceResponse(response);
}
}
}
private void ParseServiceResponse(Service.OperationResponse response)
{
// Do stuff with the response from the service operation.
}
private void ParseFailoverServiceResponse(ServiceFailover.OperationResponse response)
{
// Do stuff with the response from the failover service operation.
// This code is identical to what's in ParseServiceResponse,
// only difference is the parameter type.
}
因此try和catch块基本相同,解析函数也是如此,但所有这些中使用的对象类型都不同。
是否有更直观的方法可以在不重复代码的情况下考虑不同的类型?
这是解析函数中常见逻辑的一个例子:
private void ParseFailoverResponse(ServiceFailover.OperationResponse response)
{
// The payload is just a string containing delimited data returned by the service.
var payload = response.ResponsePayload;
if (payload.Contains("NODATA"))
{
ResultMessage.Text = "No data was returned by the service request.";
}
else
{
var _response = ParseResponseRecord(response.responsePayload);
if (_response.ResultCode == MSVResultCode.Invalid)
{
ResultMessage.Text = _response.Result;
ResultMessage.CssClass = "text-danger";
}
else if (_response.ResultCode == MSVResultCode.Valid)
{
var _payload = payload.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
// List patients and main member as returned by the medical aid.
// If none are returned, prompt the user to add the patient manually.
var patients = ParsePatientRecords(_payload);
PatientsRepeater.DataSource = patients;
PatientsRepeater.DataBind();
ResultPanel.Visible = true;
}
}
}
答案 0 :(得分:0)
为什么你不能只有一个回复?
public class Response
{
}
public abstract class GetResponseBase
{
public abstract Response GetResponse();
}
public class GetResponsePrimary : GetResponseBase
{
public override Response GetResponse()
{
return new Response();
}
}
public class GetResponseSecondary : GetResponseBase
{
public override Response GetResponse()
{
return new Response();
}
}