网络上搜索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服务的更多相关文章

  1. 完全使用接口方式调用WCF 服务

    客户端调用WCF服务可以通过添加服务引用的方式添加,这种方式使用起来比较简单,适合小项目使用.服务端与服务端的耦合较深,而且添加服务引用的方式生成一大堆臃肿的文件.本例探讨一种使用接口的方式使用WCF ...

  2. WCF入门教程(四)通过Host代码方式来承载服务

    WCF入门教程(四)通过Host代码方式来承载服务 之前已经讲过WCF对外发布服务的具体方式. WCF入门教程(一)简介 Host承载,可以是web,也可以是控制台程序等等.比WebService有更 ...

  3. 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代码方式来 ...

  4. WCF学习系列二_使用IIS发布WCF服务

    原创作者:灰灰虫的家http://hi.baidu.com/grayworm 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们使用VS2008自带的WCFSVCHost(WCF服务主机)发 ...

  5. WCF技术剖析之二十九:换种不同的方式调用WCF服务[提供源代码下载]

    原文:WCF技术剖析之二十九:换种不同的方式调用WCF服务[提供源代码下载] 我们有两种典型的WCF调用方式:通过SvcUtil.exe(或者添加Web引用)导入发布的服务元数据生成服务代理相关的代码 ...

  6. WCF开发实战系列二:使用IIS发布WCF服务

    WCF开发实战系列二:使用IIS发布WCF服务 (原创:灰灰虫的家http://hi.baidu.com/grayworm) 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们使用VS200 ...

  7. WCF开发实战系列四:使用Windows服务发布WCF服务

    WCF开发实战系列四:使用Windows服务发布WCF服务 (原创:灰灰虫的家http://hi.baidu.com/grayworm) 上一篇文章中我们通过编写的控制台程序或WinForm程序来为本 ...

  8. WCF 一步一步 发布 WCF服务 到 IIS (图)

    WCF 一步一步 发布 WCF服务 到 IIS (图) 使用VS自带的WCFSVCHost(WCF服务主机)发布WCF服务,时刻开发人员测试使用. 下面我们来看一下如何在IIS中部发布一个WCF服务. ...

  9. WCF开发实战系列二:使用IIS发布WCF服务 转

    转 http://www.cnblogs.com/poissonnotes/archive/2010/08/28/1811141.html 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们 ...

随机推荐

  1. 浅谈分布式消息技术 Kafka

    Kafka的基本介绍Kafka是最初由Linkedin公司开发,是一个分布式.分区的.多副本的.多订阅者,基于zookeeper协调的分布式日志系统(也可以当做MQ系统),常见可以用于web/ngin ...

  2. 4、redis之使用commons-pool

    增加池的配置文件redis-pool.properties: #最大能够保持idel状态的对象数 redis.pool.maxIdle=200 #当池内没有返回对象时,最大等待时间 redis.poo ...

  3. django之 文件上传功能(缺陷:无法改存放目录)

    百度云盘:django之 文件上传功能(缺陷:无法改存放目录)

  4. 搭建 Node.js 环境

    安装 Node.js 环境 任务时间:5min ~ 10min Node.js 是运行在服务端的 JavaScript, 是基于 Chrome JavaScript V8 引擎建立的平台. 下载并安装 ...

  5. VS 2013 with update 5 编译程序出现A task was cancel

    打开进程管理器看,有一堆MSBuild.exe的实例,于是用 Taskkill /IM MSBuild.exe /F 杀死了所有实例.然后再重新打开VS2013,就work了. references: ...

  6. (原)使用1080Ti显卡时安装ubuntu16.04.1及驱动的步骤

    转载请注明出处: http://www.cnblogs.com/darkknightzh/p/6811328.html 参考网址: http://www.cnblogs.com/darkknightz ...

  7. rsync的基本使用

    1,本地同步文件: rsync -avz --delete /home/ /backups/ 注意:在指定复制源时,路径是否有最后的 “/” 有不同的含义,例如: /home: 表示将整个 /home ...

  8. EasyUI DataGrid Checkbox 多选 获取选中行中的内容

    <table id='grid' class='easyui-datagrid' style='width:950px;height:405px' url='Ajax-index.php?mod ...

  9. Dapper MySql DateTime 异常

    实体类 字段类型 DateTime? ,MySQL数据库中字段类型 datetime NULL , 使用dapper扩展读取,报异常:Error Parse column: ** - Object. ...

  10. Mac OS X各版本号的历史费用和升级关系

     Mac OS X各版本号的历史费用和升级关系 OS X 10.6 Snow Leopard 早在2009年10月,Mac OS X10.6雪豹是通过光盘发送.并在英国推出时.费用£25 OS X ...