ServiceClient.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * Copyright (C) Alibaba Cloud Computing
  3. * All rights reserved.
  4. *
  5. * 版权所有 (C)阿里云计算有限公司
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using Aliyun.OSS.Util;
  11. using Aliyun.OSS.Common.Handlers;
  12. using Aliyun.OSS.Properties;
  13. namespace Aliyun.OSS.Common.Communication
  14. {
  15. /// <summary>
  16. /// The default implementation of <see cref="IServiceClient" />.
  17. /// </summary>
  18. internal abstract class ServiceClient : IServiceClient
  19. {
  20. #region Fields and Properties
  21. private readonly ClientConfiguration _configuration;
  22. internal ClientConfiguration Configuration
  23. {
  24. get { return _configuration; }
  25. }
  26. #endregion
  27. #region Constructors
  28. protected ServiceClient(ClientConfiguration configuration)
  29. {
  30. _configuration = configuration;
  31. }
  32. public static ServiceClient Create(ClientConfiguration configuration)
  33. {
  34. return new ServiceClientImpl(configuration);
  35. }
  36. #endregion
  37. #region IServiceClient Members
  38. public ServiceResponse Send(ServiceRequest request, ExecutionContext context)
  39. {
  40. SignRequest(request, context);
  41. var response = SendCore(request, context);
  42. HandleResponse(response, context.ResponseHandlers);
  43. return response;
  44. }
  45. public IAsyncResult BeginSend(ServiceRequest request, ExecutionContext context,
  46. AsyncCallback callback, object state)
  47. {
  48. SignRequest(request, context);
  49. return BeginSendCore(request, context, callback, state);
  50. }
  51. public ServiceResponse EndSend(IAsyncResult aysncResult)
  52. {
  53. var ar = aysncResult as AsyncResult<ServiceResponse>;
  54. Debug.Assert(ar != null);
  55. try
  56. {
  57. // Must dispose the async result instance.
  58. var result = ar.GetResult();
  59. ar.Dispose();
  60. return result;
  61. }
  62. catch (ObjectDisposedException)
  63. {
  64. throw new InvalidOperationException(Resources.ExceptionEndOperationHasBeenCalled);
  65. }
  66. }
  67. #endregion
  68. protected abstract ServiceResponse SendCore(ServiceRequest request, ExecutionContext context);
  69. protected abstract IAsyncResult BeginSendCore(ServiceRequest request, ExecutionContext context,
  70. AsyncCallback callback, Object state);
  71. private static void SignRequest(ServiceRequest request, ExecutionContext context)
  72. {
  73. if (context.Signer != null)
  74. context.Signer.Sign(request, context.Credentials);
  75. }
  76. protected static void HandleResponse(ServiceResponse response, IEnumerable<IResponseHandler> handlers)
  77. {
  78. foreach(var handler in handlers)
  79. handler.Handle(response);
  80. }
  81. }
  82. }