【问题标题】:Async Interception using Castle dynamic proxy使用 Castle 动态代理进行异步拦截
【发布时间】:2019-02-15 17:08:16
【问题描述】:

我正在尝试使用动态代理构建一个动态 http 客户端来拦截调用并使用它创建一个 http 请求。

我遇到的问题是异步方法:

private Task<object> PostAsync(HttpClient client, string url, HttpRequestParameters parameters, Type returnType)
    {
        return Task.Run(async () =>
        {
            var requestContent = new StringContent(Serializer.Serialize(parameters.BodyParameters));
            var httpResponse = await client.PostAsync(url, requestContent);
            var responseContent = await httpResponse.Content.ReadAsStringAsync();
            return Serializer.Deserialize(responseContent, returnType);
        });
    }

我的任务返回动态/对象,而不是拦截返回类型的 T。

我以为我可以这样使用它

 var task = PostAsync(client, url, parameters, returnType);
 invocation.ReturnValue = task;

由于将返回的任务是原始任务并且它仍然处于待处理状态,我认为它会起作用,但我得到的只是一个例外,即 Task 无法转换为我的类型的任务(在这种情况下是字符串)。

感谢大家的帮助

编辑: 我确实看到了Intercept async method,这就是我试图做的,但即使使用反射我也无法调用任务,我仍然遇到同样的异常。

【问题讨论】:

    标签: c# generics task castle-dynamicproxy dynamic-proxy


    【解决方案1】:

    我最终通过一些修改解决了这个问题:

    1. 使用基础对象创建拦截器,我使用 Moq 对象延迟创建它们并将它们存储在 ConcurrentDictionary 中以进行缓存。

      var mock = new Mock<T>();
      var pg = new ProxyGenerator();
      return pg.CreateInterfaceProxyWithTarget<T>(GetTarget(clientType), _gatewayInterceptor);
      
    2. 我将调用的返回值(在这种情况下为 T 的任务)传递给一个方法并获得了 T。

    3. 我用 T 的新任务包装了 http 调用,等待 http 调用并 从任务中返回反序列化的 T 结果。
    4. 将T的新Task赋回返回值。

      invocation.ReturnValue = GetAsync((dynamic)invocation.ReturnValue, serializer, headers, req);
      
      internal static Task<T> GetAsync<T>(Task<T> originalTask, ISerializer serializer, Headers headers, InvokeHttpRequest req)
      {
          return Task.Run(async () =>
          {
              using (HttpClient client = new HttpClient())
              {
                  var httpResponse = await PerformGetAsync(headers, req, client);
                  var jsonResponse = await httpResponse.Content.ReadAsStringAsync();
                  return ProcessResult<T>(serializer, jsonResponse);
              }
          });
      }
      

    我知道这不是最好的方法,但它对我有用。 如果有人需要,解决方案就在这里https://github.com/ErezLevip/SimpleProxyClient

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2011-08-21
      • 1970-01-01
      • 2020-05-03
      • 2011-02-26
      • 2018-10-06
      • 2018-06-23
      • 1970-01-01
      • 2012-09-16
      相关资源
      最近更新 更多