• 动态生成 WCF Client Proxy 代码 —— My Svcutil


    在《.NET Framework 3.0 之旅》中我们使用 ChannelFactory 来创建服务对象,或许你会觉得此方式有悖于 SOA 原则。没问题,现在我们使用另外一种方式来达到和 svcutil 同样的效果。 目标服务原型

    [ServiceContract]
    public interface ICalculate
    {
        [OperationContract]
        
    double Add(double a, double b);
    }

    public class CalculateService : ICalculate
    {
        
    public double Add(double a, double b)
        {
            
    return a + b;
        }
    }

     

    服务器代码
    ServiceHost host = new ServiceHost(typeof(CalculateService));
    host.AddServiceEndpoint(
    typeof(ICalculate), new BasicHttpBinding(), "http://localhost:8080/calc");

    ServiceMetadataBehavior behavior 
    = new ServiceMetadataBehavior();
    behavior.HttpGetEnabled 
    = true;
    behavior.HttpGetUrl 
    = new Uri("http://localhost:8080/calc");
    host.Description.Behaviors.Add(behavior);

    host.Open();
    我们创建了一个 ServiceMetadataBehavior,只有这样我们才能获得 WSDL / MetaData。

    动态创建客户端端代理代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using System.IO;
    using System.Reflection;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;

    Uri uri 
    = new Uri("http://localhost:8080/calc");
    MetadataExchangeClient client 
    = new MetadataExchangeClient(uri, MetadataExchangeClientMode.HttpGet);
    MetadataSet metadata 
    = client.GetMetadata();
    WsdlImporter importer 
    = new WsdlImporter(metadata);

    CodeCompileUnit ccu 
    = new CodeCompileUnit();
    CodeDomProvider provider 
    = CodeDomProvider.CreateProvider("CSharp");
    ServiceContractGenerator generator 
    = new ServiceContractGenerator(ccu);

    foreach (ContractDescription description in importer.ImportAllContracts())
    {
        generator.GenerateServiceContractType(description);
    }

    StringWriter writer 
    = new StringWriter();
    provider.GenerateCodeFromCompileUnit(ccu, writer, 
    null);

    string code = writer.ToString();
    File.WriteAllText(
    "proxy.cs", code, Encoding.Default);
    运行上述代码后,打开 proxy.cs,你看到了什么?好了,把这个文件加到客户端项目中去就 OK 了。其实利用此方式,我们还可以动态生成客户端代理程序集,实现动态调用,有关此方式,可以参考我以前写的《动态调用 WebService》。
  • 相关阅读:
    华为云招募工业智能领域合作伙伴,强力扶持+商业变现
    “不敢去怀疑代码,又不得不怀疑代码”记一次网络请求超时分析
    详解openGauss多线程架构启动过程
    站在数字化风口,工装企业如何“飞起来”
    如何化解35岁危机?华为云数据库首席架构师20年技术经验分享
    解读2022年度敏捷教练行业现状报告
    理论+案例,带你掌握Angular依赖注入模式的应用
    机器学习实践:基于支持向量机算法对鸢尾花进行分类
    8种桌面IDE CodeArts智能代码补全类型
    【CVPR2022】用于域适应语义分割的域无关先验
  • 原文地址:https://www.cnblogs.com/goody9807/p/2152860.html
Copyright © 2020-2023  润新知