123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- using System;
- using System.Reflection;
- using Bridge;
- using Newtonsoft.Json;
- namespace Cbdx
- {
- public class DataExchangeServiceFactory
- {
- private readonly ExternalDataExchangeDispatcher _dataExchangeDispatcher;
- public DataExchangeServiceFactory(ExternalDataExchangeDispatcher dataExchangeDispatcher)
- {
- _dataExchangeDispatcher = dataExchangeDispatcher;
- }
- public TInterface Create<TInterface>()
- {
- return Create<TInterface>(typeof(TInterface).Name);
- }
- 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($"Maximum 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);
- DevUtils.LogDebug($"Invoke Service:{serviceName}, Action:{methodInfo.Name}, Input:{inputJson}");
- var outputJson = _dataExchangeDispatcher.InvokeService(serviceName, methodInfo.Name, inputJson);
- DevUtils.LogDebug($"Return Service:{serviceName}, Action:{methodInfo.Name}, Return:{outputJson}");
- var errorCheck = JsonConvert.DeserializeObject<DataExchangeResultBase>(outputJson);
- if (false == errorCheck.Success)
- {
- var errorMessage = JsonConvert.DeserializeObject<DataExchangeErrorResult>(outputJson);
- throw new DataExchangeException(errorMessage.Message, errorMessage.StackTrace);
- }
- var returnType = typeof(DataExchangeDataResult<>).MakeGenericType(new[] { methodInfo.ReturnType });
- var output = JsonConvert.DeserializeObject(outputJson, returnType);
- DevUtils.LogDebug(output);
- return output["Data"];
- });
- //interface alias
- si[explicitMethodName] = implement;
- si[methodInfo.Name] = implement;
- }
- return DuckCast<TInterface>(si);
- }
- [Template("{instance}")]
- private static extern T DuckCast<T>(object instance);
- }
- }
|