wcf服务运营结果的良好实践

时间:2014-05-08 08:51:06

标签: c# .net wcf

如果我们需要发送失败/成功结果,Wcf服务的最佳做法是什么?

例如: 我们有Wcf服务,在服务后面我们有一些BussinesLogic。 我们的服务有一份运营合同:

[OperationContract] /*SomeResult*/ SendImages(Bitmap[] images);

可能的情况:

  1. 操作完成,全部成功。
  2. 位图参数不正确(位图大小或位数错误)。
  3. BussinesLogic在"坏"州。逻辑处于错误状态,我们 不知道什么时候可以再次工作。
  4. 我应该自定义fault吗?在哪?我应该使用通用fault吗?我应该enum OperationResult吗?或者maby,如果成功,任何结果都像是矫枉过正? 可能的情景数量将保持不变。

1 个答案:

答案 0 :(得分:8)

我喜欢用这种方法:

[DataContract]
public class OperationResult
{
  public OperationResult()
  {
    Errors = new List<OperationError>();
    Success = true;
  }

  [DataMember]
  public bool Success { get; set; }

  [DataMember]
  public IList<OperationError> Errors { get; set; }
}

[DataContract(Name = "OperationResultOf{0}")]
public class OperationResult<T> : OperationResult
{
  [DataMember]
  public T Result { get; set; }
}

[DataContract]
public class OperationError
{
  [DataMember]
  public string ErrorCode { get; set; }

  [DataMember]
  public string ErrorMessage { get; set; }
}

我也有一些扩展名:

  public static OperationResult WithError(this OperationResult operationResult, string errorCode,
                                          string error = null)
  {
    return operationResult.AddErrorImpl(errorCode, error);
  }

  public static OperationResult<T> WithError<T>(this OperationResult<T> operationResult, string errorCode,
                                                string error = null)
  {
    return (OperationResult<T>) operationResult.AddErrorImpl(errorCode, error);
  }

  private static OperationResult AddErrorImpl(this OperationResult operationResult, string errorCode,
                                              string error = null)
  {
    var operationError = new OperationError {Error = error ?? string.Empty, ErrorCode = errorCode};

    operationResult.Errors.Add(operationError);
    operationResult.Success = false;

    return operationResult;
  }

  public static OperationResult<T> WithResult<T>(this OperationResult<T> operationResult, T result)
  {
    operationResult.Result = result;
    return operationResult;
  }

扩展可以使用一行代码返回错误:

return retValue.WithError(ErrorCodes.RequestError);

从我的wcf服务中我永远不会抛出异常。

对不起代码墙


来电者的代码是这样的。但这一切都取决于您的要求

OperationResult res = _service.Register(username, password);

if(!res.Success)
{
    if(res.Errors.Any(x => ErrorCodes.UsernameTaken)
    {
       // show error for taken username
    }
    ...
}
相关问题