DataExchangeService.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using Bridge;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Reflection;
  5. namespace DataExchange
  6. {
  7. public class DataExchangeService
  8. {
  9. private readonly IDataExchangeApi _dataExchangeApi;
  10. public DataExchangeService(IDataExchangeApi dataExchangeApi)
  11. {
  12. _dataExchangeApi = dataExchangeApi;
  13. }
  14. public TInterface Create<TInterface>(string serviceName)
  15. {
  16. var interfaceType = typeof(TInterface);
  17. if (interfaceType.IsNested) throw new NotSupportedException("Not support nested type define");
  18. var interfaceMethodInfos = interfaceType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
  19. object si = new { };
  20. foreach (var methodInfo in interfaceMethodInfos)
  21. {
  22. if (1 != methodInfo.GetParameters().Length) throw new NotSupportedException($"Only 1 param supported, {interfaceType.FullName}::{methodInfo.Name}");
  23. var explicitMethodName = $"{interfaceType.FullName}.{methodInfo.Name}".Replace('.', '$');
  24. var implement = new Func<object, object>(input =>
  25. {
  26. //handle params and returns
  27. var inputJson = JsonConvert.SerializeObject(input);
  28. var outputJson = _dataExchangeApi.InvokeService(serviceName, methodInfo.Name, inputJson);
  29. var output = JsonConvert.DeserializeObject(outputJson, methodInfo.ReturnType);
  30. return output;
  31. });
  32. //interface alias
  33. si[explicitMethodName] = implement;
  34. si[methodInfo.Name] = implement;
  35. }
  36. return DuckCast<TInterface>(si);
  37. }
  38. [Template("{instance}")]
  39. private static extern T DuckCast<T>(object instance);
  40. }
  41. }