通过纯代码方式发布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服务,在测试的时候,我们 ...
随机推荐
- 一起talk C栗子吧(第八十五回:C语言实例--使用信号进行进程间通信二)
各位看官们,大家好,上一回中咱们说的是使用信号进行进程间通信的样例,这一回咱们接着上一回的内容,继续说该样例.闲话休提.言归正转. 让我们一起talk C栗子吧. 我们在上一回中举了使用信号进行进程间 ...
- Xamarin.Android之ListView和Adapter
一.前言 如今不管任何应用都能够看到列表的存在,而本章我们将学习如何使用Xamarin去实现它,以及如何使用适配器和自定义适配器(本文中的适配器的主要内容就是将原始的数据转换成了能够供列表控件显示的项 ...
- IF函数
语法:IF(logical_test,value_if_true,value_if_false) logical_test:表示计算结果为 TRUE 或 FALSE 的任意值或表达式 value_if ...
- python模块之importlib(py3中功能有明显加强)
# -*- coding: utf-8 -*-#python 27#xiaodeng#python模块之importlib(py3中功能有明显加强)
- SSM框架中,配置数据库连接的问题
MySQL数据库版本是8.0.11. 要用驱动:com.mysql.cj.jdbc.Driver 最主要的是数据库的连接url. 搞了半天才把问题搞明白: 数据库url后面要加上参数: jdbc:my ...
- jenkins里面使用批处理命令进行自动部署
http://blog.csdn.net/hwhua1986/article/details/47974047
- jenkins相关默认路径
安装完成后,有如下相关目录:(1)/usr/lib/jenkins/:jenkins安装目录,WAR包会放在这里.( 2 ) /etc/sysconfig/jenkins:jenkins配置文件,“端 ...
- <十一>读<<大话设计模式>>之抽象工厂模式
学习设计模式有一段时间了,对设计模式有一个体会,就是没那么难.就是设计程序遵循一些原则,让代码可复用,在改动的时候不用涉及太多的类,扩展方便.抽象工厂模式名字听起来抽象.但理解起来一点也不抽象,用语言 ...
- TCP KeepAlive的几个附加选项
TCP_KEEPALIVE选项只是一个开关,Linux中默认的Keepalive的选项如下: $sudo sysctl -a | grep keepalive net.ipv4.tcp_keepali ...
- sql和hql的区别
转自:https://blog.csdn.net/lxf512666/article/details/52820368 hql是面向对象查询,格式:from + 类名 + 类对象 + where + ...