SilverLight企業應用框架設計【三】服務端設計


一:緩存服務類型與方法

客戶端請求的時候

為了方便的知道請求的類型與類型所包含的方法

我們把服務類型和方法緩存到靜態字典中了

代碼如下

    public class WCFRouteTable
    {
        static Dictionary<string, Type> routeService;
        static Dictionary<string, MethodInfo> routeMethods;
        static WCFRouteTable()
        {
            routeService = new Dictionary<string, Type>();
            routeMethods = new Dictionary<string, MethodInfo>();
            var ass = (typeof(WCFRouteTable)).Assembly;
            var ts = ass.GetTypes();
            foreach (var t in ts)
            {
                if (t.FullName.StartsWith("RTMDemo.Host.WCF"))
                {
                    routeService.Add(t.FullName, t);
                    foreach (var m in t.GetMethods())
                    {
                        var mName = string.Format("{0}.{1}", t.FullName, m.Name);
                        routeMethods.Add(mName, m);
                    }
                }
            }
        }
        public static Type GetWCFType(string key)
        {
            Type result = null;
            if (routeService.ContainsKey(key))
            {
                result = routeService[key];
            }
            return result;
        }
        public static MethodInfo GetMethodInfo(string key)
        {
            MethodInfo result = null;
            if (routeMethods.ContainsKey(key))
            {
                result = routeMethods[key];
            }
            return result;
        }

    }

二:托管HTTP請求

在webconfig中增加module以托管請求

    <modules>
            <add name="WcfHttpModule" type="RTMDemo.Host.WCFHttpModule, RTMDemo.Host"/>
    </modules>

托管請求對應的類的代碼如下

    public class WCFHttpModule:IHttpModule
    {
        public void Dispose() { }
        /// <summary>
        /// 托管請求
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += (sender, args) =>
            {
                string relativeAddress = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Remove(0, 2);
                Type serviceType = WCFRouteTable.GetWCFType(relativeAddress);
                if (null == serviceType)
                {
                    return;
                }
                IHttpHandler handler = new WCFHandler(serviceType);
                context.Context.RemapHandler(handler);
            };
        }
    }

通過這行代碼

Type serviceType = WCFRouteTable.GetWCFType(relativeAddress);

用戶只要請求如下路徑

http://localhost/RTMDemo.Host/RTMDemo.Host.WCF.MenuService

就會得到MenuService的類型

然后把服務類型傳給指定的處理程序

三:處理請求

在WCFHandler類中最重要的莫過於

處理請求的方法

代碼如下

/// <summary>
        /// 處理請求
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                List<object> paramList = new List<object>();
                JavaScriptSerializer jss = new JavaScriptSerializer();
                var MethodKey = context.Request["MethodKey"];
                var minfo = WCFRouteTable.GetMethodInfo(MethodKey);
                var si = new MethodInvoker(minfo);
                ParameterInfo[] ps = minfo.GetParameters();
                var pstrs = context.Request.Form.AllKeys.OrderBy(m=>m).ToArray();
                var pIndex = 0;
                for(var i=0;i<pstrs.Length;i++)
                {
                    if (string.IsNullOrEmpty(pstrs[i]))
                    {
                        continue;
                    }
                    if (pstrs[i].StartsWith("p"))
                    {
                        var pStr = context.Request[pstrs[i]];
                        var obj = jss.Deserialize<object>(pStr);
                        var bts = Encoding.UTF8.GetBytes(pStr);
                        MemoryStream mss = new MemoryStream(Encoding.UTF8.GetBytes(pStr));
                        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(ps[pIndex].ParameterType);                
                        var p = jsonSerializer.ReadObject(mss);
                        paramList.Add(p);
                        pIndex += 1;
                    }
                }

                //todo:此處性能不佳
                var instance = Activator.CreateInstance(ServiceType);
                var result = si.Execute(instance,paramList.ToArray());
                var ss = jss.Serialize(result);

                context.Response.ClearContent();
                context.Response.ContentEncoding = Encoding.UTF8;
                context.Response.ContentType = "application/json; charset=utf-8";
                context.Response.Write(ss);
                context.Response.Flush();
            }
            catch
            {
                context.Response.Write("我們不提供此服務的元數據~<br />");
                context.Response.Write("@@@@@@~<br />@@@@@@@~");
                return;
            }
        }
    }

注意:首先說這段代碼還有很大的優化空間;也未經過嚴格的測試;但思路基本就是這樣的

處理請求主要做了如下幾步工作:

1.

先根據請求POST上來的信息得到准備執行的方法

var MethodKey = context.Request["MethodKey"];
var minfo = WCFRouteTable.GetMethodInfo(MethodKey);

MethodInvoker稍后再講

2.

按順序取出了方法的參數,並用DataContractJsonSerializer反序列化成對象

方法參數都是用JSON字符串傳遞的

3.

通過反射創建了服務的實例

然后調用該實例的方法

得到方法的返回值,並序列化成JSON字符串

4.

把返回值以JSON的形式輸出給客戶端

四:其他

1.

MethodInvoker是用的老趙的類;具體是哪篇文章,我已經找不到了。

public class MethodInvoker
    {
        private Func<object, object[], object> m_execute;

        public MethodInvoker(MethodInfo methodInfo)
        {
            this.m_execute = this.GetExecuteDelegate(methodInfo);
        }

        public object Execute(object instance, params object[] parameters)
        {
            return this.m_execute(instance, parameters);            
        }

        private Func<object, object[], object> GetExecuteDelegate(MethodInfo methodInfo)
        {
            ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "instance");
            ParameterExpression parametersParameter = Expression.Parameter(typeof(object[]), "parameters");

            List<Expression> parameterExpressions = new List<Expression>();
            ParameterInfo[] paramInfos = methodInfo.GetParameters();
            for (int i = 0; i < paramInfos.Length; i++)
            {
                var ce = Expression.Constant(i);
                BinaryExpression valueObj = Expression.ArrayIndex(parametersParameter,ce);
                UnaryExpression valueCast = Expression.Convert(valueObj, paramInfos[i].ParameterType);
                parameterExpressions.Add(valueCast);
            }
            var instanceE = Expression.Convert(instanceParameter, methodInfo.ReflectedType);
            Expression instanceCast = methodInfo.IsStatic ? null : instanceE;
            MethodCallExpression methodCall = Expression.Call(instanceCast, methodInfo, parameterExpressions);
            if (methodCall.Type == typeof(void))
            {
                Expression<Action<object, object[]>> lambda = Expression.Lambda<Action<object, object[]>>(methodCall, instanceParameter, parametersParameter);
                Action<object, object[]> execute = lambda.Compile();
                return (instance, parameters) =>
                {
                    execute(instance, parameters);
                    return null;
                };
            }
            else
            {
                UnaryExpression castMethodCall = Expression.Convert(methodCall, typeof(object));
                Expression<Func<object, object[], object>> lambda =Expression.Lambda<Func<object, object[], object>>(castMethodCall, instanceParameter, parametersParameter);
                return lambda.Compile();
            }
        }
    }

2.

服務類和數據訪問的類沒有什么特殊的

我這里只公布一個服務的類

    public class MenuService
    {
        public List<MenuM> GetAllMenu()
        {            
            using (var DA = new MenuDA())
            {
                var result = DA.GetAllMenu();
                return result;
            }
        }
        public void DelMenu(Guid Id)
        {
            using (var DA = new MenuDA())
            {
                DA.DelMenu(Id);
            }
        }
        public void AddMenu(MenuM m)
        {
            using (var DA = new MenuDA())
            {
                DA.AddMenu(m);
            }
        }
        public void UpdateMenu(MenuM m)
        {
            using (var DA = new MenuDA())
            {
                DA.UpdateMenu(m);
            }
        }
    }

MenuDa就是數據訪問類了

很普通,就不在公布代碼了

3.

完成這些工作之后

我們只要在客戶端構造好表單

然后把表單POST到指定的路徑

就能完成服務的訪問了!

 

---------------------------------------------------------------

喜歡的話~請大家推薦我的文章

謝謝~

我真的很需要你們的支持


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM