12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- using Bridge;
- using Newtonsoft.Json;
- using System;
- using System.Reflection;
- namespace DataExchange
- {
- public class DataExchangeService
- {
- private readonly IDataExchangeApi _dataExchangeApi;
- public DataExchangeService(IDataExchangeApi dataExchangeApi)
- {
- _dataExchangeApi = dataExchangeApi;
- }
- public TInterface Create<TInterface>(string serviceName)
- {
- var interfaceType = typeof(TInterface);
- if (interfaceType.IsNested) throw new NotSupportedException("Not support nested type define");
- var interfaceMethodInfos = interfaceType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
- object si = new { };
- foreach (var methodInfo in interfaceMethodInfos)
- {
- if (1 != methodInfo.GetParameters().Length) throw new NotSupportedException($"Only 1 param supported, {interfaceType.FullName}::{methodInfo.Name}");
- var explicitMethodName = $"{interfaceType.FullName}.{methodInfo.Name}".Replace('.', '$');
- var implement = new Func<object, object>(input =>
- {
- //handle params and returns
- var inputJson = JsonConvert.SerializeObject(input);
- var outputJson = _dataExchangeApi.InvokeService(serviceName, methodInfo.Name, inputJson);
- var output = JsonConvert.DeserializeObject(outputJson, methodInfo.ReturnType);
- return output;
- });
- //interface alias
- si[explicitMethodName] = implement;
- si[methodInfo.Name] = implement;
- }
- return DuckCast<TInterface>(si);
- }
- [Template("{instance}")]
- private static extern T DuckCast<T>(object instance);
- }
- }
|