DataExchangeServiceFactory.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Bridge;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Reflection;
  6. namespace CefBridgeDataExchange
  7. {
  8. public class DataExchangeServiceFactory
  9. {
  10. private readonly ExternalDataExchangeDispatcher _dataExchangeDispatcher;
  11. public DataExchangeServiceFactory(ExternalDataExchangeDispatcher dataExchangeDispatcher)
  12. {
  13. _dataExchangeDispatcher = dataExchangeDispatcher;
  14. }
  15. public TInterface Create<TInterface>()
  16. {
  17. return Create<TInterface>(typeof(TInterface).Name);
  18. }
  19. public TInterface Create<TInterface>(string serviceName)
  20. {
  21. var interfaceType = typeof(TInterface);
  22. if (interfaceType.IsNested) throw new NotSupportedException("Not support nested type define");
  23. var interfaceMethodInfos = interfaceType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
  24. object si = new { };
  25. foreach (var methodInfo in interfaceMethodInfos)
  26. {
  27. if (1 < methodInfo.GetParameters().Length) throw new NotSupportedException($"Maximum 1 param supported, {interfaceType.FullName}::{methodInfo.Name}");
  28. var explicitMethodName = $"{interfaceType.FullName}.{methodInfo.Name}".Replace('.', '$');
  29. var implement = new Func<object, object>(input =>
  30. {
  31. //handle params and returns
  32. var inputJson = JsonConvert.SerializeObject(input);
  33. DevUtils.LogDebug($"Invoke Service:{serviceName}, Action:{methodInfo.Name}, Input:{inputJson}");
  34. var outputJson = _dataExchangeDispatcher.InvokeService(serviceName, methodInfo.Name, inputJson);
  35. DevUtils.LogDebug($"Return Service:{serviceName}, Action:{methodInfo.Name}, Return:{outputJson}");
  36. var errorCheck = JsonConvert.DeserializeObject<DataExchangeResultBase>(outputJson);
  37. if (false == errorCheck.Success)
  38. {
  39. var errorMessage = JsonConvert.DeserializeObject<DataExchangeErrorResult>(outputJson);
  40. throw new DataExchangeException(errorMessage.Message, errorMessage.StackTrace);
  41. }
  42. var returnType = typeof(DataExchangeDataResult<>).MakeGenericType(new[] { methodInfo.ReturnType });
  43. var output = JsonConvert.DeserializeObject(outputJson, returnType);
  44. DevUtils.LogDebug(output);
  45. return output["Data"];
  46. });
  47. //interface alias
  48. si[explicitMethodName] = implement;
  49. si[methodInfo.Name] = implement;
  50. }
  51. return DuckCast<TInterface>(si);
  52. }
  53. [Template("{instance}")]
  54. private static extern T DuckCast<T>(object instance);
  55. }
  56. }