通过纯代码方式发布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服务,在测试的时候,我们 ...
随机推荐
- Spring MVC的Post请求参数中文乱码的原因&处理
一.项目配置: Spring 4.4.1-RELEASE Jetty 9.3.5 JDK 1.8 Servlet 3.1.0 web.xml文件中没有配置编解码Filter 二.实际遇到的问题:客户端 ...
- Linux内核中的软中断、tasklet和工作队列具体解释
[TOC] 本文基于Linux2.6.32内核版本号. 引言 软中断.tasklet和工作队列并非Linux内核中一直存在的机制,而是由更早版本号的内核中的"下半部"(bottom ...
- MSVC下使用Boost的自动链接
简述 好久没有用过boost库了,以前用也是在linux下,需要哪个部分就添加哪个部分到Makefile中. 最近要在Windows下使用,主要是mongocxx库依赖它,不想自己去编译它了,就直接在 ...
- fnmatch源码阅读
源码下载地址如下: http://web.mit.edu/freebsd/csup/fnmatch.h http://web.mit.edu/freebsd/csup/fnmatch.c 代码整体不错 ...
- 微信小程序,创业新选择
微信小程序,创业新选择 创业者们 总是站在时代的风口浪尖,他们踌躇满志无所畏惧,这大概就是梦想的力量.但是,如果没有把梦想拆解成没有可预期的目标和可执行的实现路径那么一切都只能叫做梦想. 小程序 张小 ...
- keras中的模型保存和加载
tensorflow中的模型常常是protobuf格式,这种格式既可以是二进制也可以是文本.keras模型保存和加载与tensorflow不同,keras中的模型保存和加载往往是保存成hdf5格式. ...
- at com.mysql.jdbc.SQLError.createSQLException
WARN run, com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@1de6191 -- APPARENT DEA ...
- memcached全面剖析--5. memcached的应用和兼容程序
我是Mixi的长野.memcached的连载终于要结束了.到上次为止,我们介绍了与memcached直接相关的话题,本次介绍一些mixi的案例和实际应用上的话题,并介绍一些与memcached兼容的程 ...
- 【Oracle】Oracle的内外连接
目录结构: contents structure [+] Oracle的内外连接 内连接 等值连接 非等值连接 自连接 外连接 外连接的特点 如何实现外连接 SQL99的内外连接 SQL99的内连接 ...
- 创建 maven maven-archetype-quickstart 项目抱错问题解决方法
问题: eclipse装m2eclipse的时候装完后创建项目的时候报错: Unable to create project from archetype org.apache.maven.arche ...