繁体   English   中英

轻量级动态WCF客户端

[英]Lightweight dynamic WCF client

我必须使用一些WCF服务,但我不想实现所有必需的类。 甚至是动态的。 我想将WCF服务用作传输工具,并且只关心对我而言重要的事情。

一个很好的例子是发送带有参数的SQL并返回响应。 SQL可能不同,参数也不同,当然响应也不同。 有些事情是必需的,有些是静态的,有些是动态的-我可以全力以赴,但是我不想为每种情况创建类。

让我们举个例子,假设数据以JSON传递。

请求:

{ "program":"sqlSelect", "sql":"select siesta from dual"}

回答:

{"sysdate":"02/03/2016"}

另一个要求

{ "program":"sqlSelect", "sql":"select name from user where id<>:a","a":"alex"} 

响应

{"rows":[{ "name":"Bob"},{"name":"Bill"}], "errorCode":""}

困扰我的是必须为每个请求/响应编写/生成特殊类。 当然,一般的建议是使用带有简单输入/请求的客户端/服务器-只是包含json的字符串。 或者,更好的方法是,创建通用对象,该对象足够复杂以处理所有可能的情况。 但是,即使第二个示例也显示了它可能有多么复杂。 最糟糕的是-服务器不是我的专长。 我只是消费者,可以得到服务器给我的东西。 我可以创建/转换请求以适应服务器需求,但是响应应该以最简单的方式呈现。

我的假设是,传输是XML,如果可以在将其转换为对象之前转换为JSON,然后将其转换为json,那么我可以使用类似

if (answer.errorCode=="") SomeProcess(answer.rows[0].name);

没有课程Answer,Rows,Row。

有什么建议可以到达那里吗?

反思就是答案。 根据json的值创建服务对象,基于json调用适当的服务,并返回包装到json的答案。 这是简单的代码,它将调用任何WCF客户端,调用任何操作,关闭客户端并以字符串形式返回结果:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Web.Script.Serialization;

namespace MyNameSpace
{
    class Json2Wcf
    {
        private static void Main(string[] args)
        {
            Debug.WriteLine(Json2Wcf.CallWcf("{'WcfServiceClass':'MyServiceClient', 'WcfServiceAction':'Heartbeat'}"));
        }

        public static string CallWcf(string json)
        {
            var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(json);

            Type typeWcfServiceClass = Type.GetType(dict["WcfServiceClass"], true);

            object instanceWcfServiceClass = Activator.CreateInstance(typeWcfServiceClass);

            MethodInfo methodWcfServiceAction = typeWcfServiceClass.GetMethod(dict["WcfServiceAction"]);
            object result = methodWcfServiceAction.Invoke(instanceWcfServiceClass, null);

            typeWcfServiceClass.GetMethod("Close").Invoke(instanceWcfServiceClass, null);

            return "Answer="+result;
        }
    }
}

当然会返回

Answer=thub-thub

稍加修改,它就可以调用带参数的动作,并返回包装在json中的复杂值。 此示例是基本原理的简单说明,以及如何调用任何WCF服务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM