using System; using System.Collections; using System.Collections.Generic; using Zhaizj.Framework.DI; using Zhaizj.Framework.Reflection; using Zhaizj.Framework.SOA.Controls; namespace Zhaizj.Framework.SOA { /// /// 获取服务的工具类 /// public class ServiceContext { /// /// 根据 id 获取服务 /// /// /// public static Service Get( int serviceId ) { return (new Service().findById( serviceId ) as Service); } /// /// 获取所有服务 /// /// public static IList GetAll() { return new Service().findAll(); } /// /// 获得某分类下的所有服务(tag当做分类法使用) /// /// /// /// public static IList GetByTag( String tag, String ownerType ) { IList list = new ArrayList(); IList all = GetAll(); foreach (Service service in all) { if (hasTag( service.Tags, tag ) && isOwner( ownerType, service.GetOwnerTypes() ) && service.Status != ServiceStatus.ListForbidden) { list.Add( service ); } } return list; } private static Boolean isOwner( String ownerType, String[] ownerTypes ) { foreach (String o in ownerTypes) { if (ownerType.Equals( o )) return true; } return false; } /// /// 根据服务 id 和参数,调用服务,返回服务运行的结果 /// /// /// 服务的参数 /// 默认参数 /// public static IList GetData( int serviceId, Dictionary serviceParamValues, Dictionary defaultValues ) { ArrayList argList = new ArrayList(); Service service = Get( serviceId ); IList parms = service.GetParams(); for (int i = 0; i < parms.Count; i++) { String pkey = "param" + i; String val = serviceParamValues.ContainsKey( pkey ) ? serviceParamValues[pkey] : null; Object argValue = ((ParamControl)parms[i]).ChangeType( val ); argList.Add( argValue ); } foreach (KeyValuePair pair in defaultValues) { Object argValue = getValue( service, pair ); argList.Add( argValue ); } object[] args = argList.ToArray(); Object objService = ObjectContext.GetByType( service.Type ); return (ReflectionUtil.CallMethod( objService, service.Method, args ) as IList); } private static Object getValue( Service service, KeyValuePair pair ) { Dictionary pd = service.GetParamDefault(); String valueType = pd[pair.Key]; if (valueType.Equals( "int" )) return cvt.ToInt( pair.Value ); return pair.Value; } private static Boolean hasTag( String svcTag, String tag ) { if (strUtil.HasText( svcTag )) { tag = tag.Trim(); String[] strArray = svcTag.Split( new[] { ',', '/', ' ', '|' } ); foreach (String str in strArray) { if (str.Trim() == tag) { return true; } } } return false; } } }