WCF是一个使用托管代码以及面向服务的统一的应用框架。那么它的出现,给开发人员带来了非常大的好处。在这里我们就先来给大家介绍一种比较简单的应用技巧,WCF动态创建代码的相关实现方法。
目标服务原型
- [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。
WCF动态创建代码:
- 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,你看到了什么?好了,把这个文件加到客户端项目中去就完成了WCF动态创建代码的操作。
【编辑推荐】