通过纯代码方式发布WCF服务
网络上搜索WCF服务,一般是寄宿在IIS,通过WebConfig方式配服务地址,接口类型等信息,但是对于我这样的懒人,目前项目在开发阶段,实在不愿意每次添加新服务就更新配置文件,于是使用了反射来加载服务接口,并用控制台程序发布服务,贴上代码如下。 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Configuration;
using Nebula.Proxy;
using System.Reflection;
using System.Configuration;
using System.Xml;
namespace MES_WCFService
{
public class HostIniter
{
public HostIniter()
{ }
private ServiceHostCollection hosts; private Type[] interfaceTypes;
private Type[] implTypes;
private string addressBase;
private string tcpPort;
private string httpPort;
private string basehttpPort;
/// <summary>
/// 通过反射获取所有服务接口及其实现类
/// </summary>
private void ScanService()
{
interfaceTypes = Assembly.Load(ConfigurationManager.AppSettings["interfaceDLLName"]).GetTypes();
implTypes = Assembly.Load(ConfigurationManager.AppSettings["implDLLName"]).GetTypes(); } public ServiceHostCollection InitHost()
{ hosts = new ServiceHostCollection();
addressBase = ConfigurationManager.AppSettings["baseAddress"];
tcpPort = ConfigurationManager.AppSettings["tcpPort"];
httpPort = ConfigurationManager.AppSettings["httpPort"];
basehttpPort = ConfigurationManager.AppSettings["basehttpPort"];
ScanService();
foreach (Type implType in implTypes)
{
try
{ if (!typeof(IWCFService).IsAssignableFrom(implType))
{
continue;
}
string baseNameSpace= "http://" + addressBase + ":" + httpPort + "/WCFService/";
string address = baseNameSpace + implType.Name;
Uri baseAddress = new Uri(address);
ServiceHost host = new ServiceHost(implType, baseAddress); //
Console.WriteLine("Add:" + implType.FullName);
Console.WriteLine("Address:" + address);
host.Description.Namespace = baseNameSpace;
host.Description.Name = implType.Name; ServiceSecurityAuditBehavior secBehacior = new ServiceSecurityAuditBehavior(); secBehacior.MessageAuthenticationAuditLevel = AuditLevel.None;
secBehacior.ServiceAuthorizationAuditLevel = AuditLevel.None; host.Description.Behaviors.Add(secBehacior); // secBehacior. ServiceMetadataBehavior metaBehavior = new ServiceMetadataBehavior();
metaBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
metaBehavior.HttpGetEnabled = true; ServiceDebugBehavior debugBehavior = host.Description.Behaviors[typeof(ServiceDebugBehavior)] as ServiceDebugBehavior;
debugBehavior.IncludeExceptionDetailInFaults = true; host.Description.Behaviors.Add(metaBehavior); Type t = host.GetType();
object obj = t.Assembly.CreateInstance("System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior", true,
BindingFlags.CreateInstance | BindingFlags.Instance |
BindingFlags.NonPublic, null, new object[] { false, Int32.MaxValue },
null, null);
IServiceBehavior myServiceBehavior = obj as IServiceBehavior;
if (myServiceBehavior != null)
{
host.Description.Behaviors.Add(myServiceBehavior);
// Console.WriteLine("Add DataContractSerializerServiceBehavior !");
} ////host.Description.Behaviors.Add(debugBehavior);
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType == typeof(IWCFService))
{
continue;
} if (interfaceType.IsAssignableFrom(implType))
{
//本来是WSHttpBinding 为了让Java能调用到这些服务,遂改BasicHttpBinding BasicHttpBinding wsBinding = new BasicHttpBinding();
wsBinding.Security.Mode =BasicHttpSecurityMode.None;
wsBinding.MaxBufferPoolSize = ;
wsBinding.MaxReceivedMessageSize = int.MaxValue; wsBinding.ReaderQuotas.MaxStringContentLength = 0xfffffff;
wsBinding.ReaderQuotas.MaxArrayLength = 0xfffffff;
wsBinding.ReaderQuotas.MaxBytesPerRead = 0xfffffff;
wsBinding.ReaderQuotas.MaxDepth = 0xfffffff;
wsBinding.MessageEncoding = WSMessageEncoding.Text;
wsBinding.TextEncoding = Encoding.UTF8;
wsBinding.OpenTimeout = new TimeSpan(, , );
wsBinding.ReceiveTimeout = new TimeSpan(, , );
wsBinding.SendTimeout = new TimeSpan(, , ); ContractDescription contractDescription = ContractDescription.GetContract(interfaceType);
ServiceEndpoint httpEndpoint = new ServiceEndpoint(contractDescription, wsBinding, new EndpointAddress(baseAddress));
httpEndpoint.Name = "http" + implType.Name;
host.Description.Endpoints.Add(httpEndpoint); NetTcpBinding netTcpBinding = new NetTcpBinding() { Security = new NetTcpSecurity { Mode = SecurityMode.None } };
netTcpBinding.Security.Mode = SecurityMode.None;
netTcpBinding.MaxBufferPoolSize = ;
netTcpBinding.MaxReceivedMessageSize = int.MaxValue;
netTcpBinding.ReaderQuotas.MaxStringContentLength = 0xfffffff;
netTcpBinding.ReaderQuotas.MaxArrayLength = 0xfffffff;
netTcpBinding.ReaderQuotas.MaxBytesPerRead = 0xfffffff;
netTcpBinding.ReaderQuotas.MaxDepth = 0xfffffff;
netTcpBinding.OpenTimeout = new TimeSpan(, , );
netTcpBinding.ReceiveTimeout = new TimeSpan(, , );
netTcpBinding.SendTimeout = new TimeSpan(, , );
ServiceEndpoint tcpEndpoint = new ServiceEndpoint(contractDescription, netTcpBinding, new EndpointAddress("net.tcp://" + addressBase + ":" + tcpPort + "/WCFService/" + implType.Name));
tcpEndpoint.Name = "tcp" + implType.Name;
host.Description.Endpoints.Add(tcpEndpoint); host.AddServiceEndpoint(
ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexHttpBinding(),
"mex"
); break;
}
}
//添加自定义的 Behavior
host.Description.Behaviors.Add(new MesServiceInterceptorAttribute()); hosts.Add(host);
} catch (Exception commProblem)
{ Console.WriteLine("There was a problem with this type ;"+implType.FullName);
Console.WriteLine("Message:" + commProblem.Message);
Console.WriteLine("StackTrace:" + commProblem.StackTrace);
Console.Read();
} }
return hosts;
} }
}
MesServiceInterceptorAttribute的代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.ServiceModel.Channels; namespace MES_WCFService
{
[AttributeUsage(AttributeTargets.Class)]
public class MesServiceInterceptorAttribute : Attribute, IServiceBehavior
{
protected MesOperationInterceptorAttribute CreateOperationInterceptor()
{
return new MesOperationInterceptorAttribute();
} public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase host)
{
foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
{
foreach (OperationDescription operation in endpoint.Contract.Operations)
{
bool checkresult = false;
foreach (IOperationBehavior behavior in operation.Behaviors)
{
if (behavior is MesOperationInterceptorAttribute)
{
checkresult = true;
break;
}
}
if (!checkresult)
{
operation.Behaviors.Add(CreateOperationInterceptor());
}
}
}
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{ } public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{ }
}
}
MesOperationInterceptorAttribute的: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
namespace MES_WCFService
{
[AttributeUsage(AttributeTargets.Method)]
public class MesOperationInterceptorAttribute : Attribute, IOperationBehavior
{
//private InterceptionType m_InteType = InterceptionType.None;
private string _operatName;
public MesOperationInterceptorAttribute() { } //public MesOperationInterceptorAttribute(InterceptionType inteType)
//{
// this.m_InteType = inteType;
//} protected MesInvoker CreateInvoker(IOperationInvoker oldInvoker)
{
return new MesInvoker(oldInvoker, _operatName);
} public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{ } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{ } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
IOperationInvoker oldInvoker = dispatchOperation.Invoker;
_operatName = dispatchOperation.Name;
dispatchOperation.Invoker = CreateInvoker(oldInvoker);
} public void Validate(OperationDescription operationDescription)
{ }
}
}
通过纯代码方式发布WCF服务的更多相关文章
- 完全使用接口方式调用WCF 服务
客户端调用WCF服务可以通过添加服务引用的方式添加,这种方式使用起来比较简单,适合小项目使用.服务端与服务端的耦合较深,而且添加服务引用的方式生成一大堆臃肿的文件.本例探讨一种使用接口的方式使用WCF ...
- WCF入门教程(四)通过Host代码方式来承载服务
WCF入门教程(四)通过Host代码方式来承载服务 之前已经讲过WCF对外发布服务的具体方式. WCF入门教程(一)简介 Host承载,可以是web,也可以是控制台程序等等.比WebService有更 ...
- WCF入门教程(四)通过Host代码方式来承载服务 一个WCF使用TCP协议进行通协的例子 jquery ajax调用WCF,采用System.ServiceModel.WebHttpBinding System.ServiceModel.WSHttpBinding协议 学习WCF笔记之二 无废话WCF入门教程一[什么是WCF]
WCF入门教程(四)通过Host代码方式来承载服务 Posted on 2014-05-15 13:03 停留的风 阅读(7681) 评论(0) 编辑 收藏 WCF入门教程(四)通过Host代码方式来 ...
- WCF学习系列二_使用IIS发布WCF服务
原创作者:灰灰虫的家http://hi.baidu.com/grayworm 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们使用VS2008自带的WCFSVCHost(WCF服务主机)发 ...
- WCF技术剖析之二十九:换种不同的方式调用WCF服务[提供源代码下载]
原文:WCF技术剖析之二十九:换种不同的方式调用WCF服务[提供源代码下载] 我们有两种典型的WCF调用方式:通过SvcUtil.exe(或者添加Web引用)导入发布的服务元数据生成服务代理相关的代码 ...
- WCF开发实战系列二:使用IIS发布WCF服务
WCF开发实战系列二:使用IIS发布WCF服务 (原创:灰灰虫的家http://hi.baidu.com/grayworm) 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们使用VS200 ...
- WCF开发实战系列四:使用Windows服务发布WCF服务
WCF开发实战系列四:使用Windows服务发布WCF服务 (原创:灰灰虫的家http://hi.baidu.com/grayworm) 上一篇文章中我们通过编写的控制台程序或WinForm程序来为本 ...
- WCF 一步一步 发布 WCF服务 到 IIS (图)
WCF 一步一步 发布 WCF服务 到 IIS (图) 使用VS自带的WCFSVCHost(WCF服务主机)发布WCF服务,时刻开发人员测试使用. 下面我们来看一下如何在IIS中部发布一个WCF服务. ...
- WCF开发实战系列二:使用IIS发布WCF服务 转
转 http://www.cnblogs.com/poissonnotes/archive/2010/08/28/1811141.html 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们 ...
随机推荐
- Android开发之欢迎界面标准
import java.util.ArrayList; import android.app.Activity; import android.content.SharedPreferences; i ...
- V-rep学习笔记:Reflexxes Motion Library 3
路径规划 VS 轨迹规划 轨迹规划的目的是将输入的简单任务描述变为详细的运动轨迹描述.注意轨迹和路径的区别:Trajectory refers to a time history of positio ...
- XPages访问关系型数据库技术与最佳实践
XPage 对于 Domino 开发人员的一大好处就是能够很方便和高效的访问关系型数据库.本文通过实例代码展现了在 XPage 中访问关系型数据库的具体步骤 , 同时讲解了一些在 XPage 中高效访 ...
- PHP视频学习一 mysql
设置mysql.exe文件目录到环境变量Path中去,可能在cmd下面使用mysql,wind7试了一下好像要重启以后才生效 什么是数据库 数据库就是存储数据的地方,是保存在计算机(硬盘/内存)中的数 ...
- java第三节 面向对象(上)
//第三讲 //面向对象(上) /* 理解面向对象的概念 面向过程 在一个结构体中定义窗体的大小,位置,颜色,背景等属性,对窗口操作的函数窗口本身的定义没有任何关系 如HideWindow, Move ...
- yum安装提示错误Thread/process failed: Thread died in Berkeley DB library
问题描述: yum 安装更新提示 rpmdb: Thread/process failed: Thread died in Berkeley DB library 问题解决: 01.删除yum临时库文 ...
- Ubuntu18.04下的 Android Studio 3.1.2
Android Studio安装 参考官网上的安装说明 # 安装依赖 :i386 lib32z1 libbz2-1.0:i386 安装openjdk (Update 2018-08-21: 这次重装U ...
- Golang Json文件解析为结构体工具-json2go
代码地址如下:http://www.demodashi.com/demo/14946.html 概述 json2go是一个基于Golang开发的轻量json文件解析.转换命令行工具,目前支持转换输出到 ...
- 你想知道的关于JavaScript作用域的一切(译)
原文链接: Everything you wanted to know about JavaScript scope 原文作者: Todd Motto JavaScript中有许多章节是关于scope ...
- Xcode全局替换内容,一键Replace
有时需要在整个项目里,全局修改某一段话或文字,可以这样快速实现: 1.打开查找功能 2.输入你要替换的内容 比如,我这边想全局修改作者名称 3.点击Find,会出现一个框,会有replace出来,就和 ...