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(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(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(si); } [Template("{instance}")] private static extern T DuckCast(object instance); } }