您的位置:首页 > 其它

WCF寄宿

2016-03-08 21:44 585 查看
WCF可以寄宿在很多地方,常见的有IIS和系统服务,对于稳定性要求高的场合,用系统服务来运行WCF应该是比较好的选择

布署方法还是比较简单的:

1. 创建一个系统服务项目,常规的代码就不写了,主要是app.confg中的wcf配置

<system.serviceModel>
<services>
<service name="Campus.RemoteAPI.RemoteAPIService" behaviorConfiguration="RemoteAPIServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/RemoteAPIService"/>
</baseAddresses>
</host>
<endpoint address="" binding="wsHttpBinding" contract="Campus.RemoteAPI.IRemoteAPIService"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="RemoteAPIServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>


2. 在服务的OnStart事件启动,在OnStop停止

public ServiceHost serviceHost = null;
protected override void OnStart(string[] args)
{
if (serviceHost != null)
{
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(RemoteAPIService));
serviceHost.Open();
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}


3. 在Installer里面,安装服务

public partial class Installer1 : System.Configuration.Install.Installer
{
private ServiceProcessInstaller myServiceProcessInstaller;
private ServiceInstaller myServiceInstaller;
public Installer1()
{
this.myServiceProcessInstaller = new ServiceProcessInstaller();
this.myServiceInstaller = new ServiceInstaller();

// 安装
// 用户名 和 密码
this.myServiceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.myServiceProcessInstaller.Username = null;
this.myServiceProcessInstaller.Password = null;

// 服务名称,这样可以在net stop XX 里面使用了
// 启动类型
this.myServiceInstaller.ServiceName = "CampusRemoteAPI";
this.myServiceInstaller.StartType = ServiceStartMode.Automatic;

// 加入
this.Installers.AddRange(new Installer[] { this.myServiceProcessInstaller, this.myServiceInstaller });
}
}


记住:系统服务对应的帐号一定要是 ServiceAccount.LocalSystem,如果是选择了ServiceAccount.LocalService,就会出现启动失败,因为WCF需要开启端口监听,要比较高的权限。如果用LocalService,在OnSart会捕捉到类似以下异常

Message:拒绝访问。

<br />Source:System

<br />StackTrace: 在 System.Net.HttpListener.AddAllPrefixes()

在 System.Net.HttpListener.Start()

在 System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()

<br />==============================<br />

<br />Message:HTTP 无法注册 URL http://+:8000/RemoteAPIService/。进程不具有此命名空间的访问权限(有关详细信息,请参见 http://go.microsoft.com/fwlink/?LinkId=70353)。

<br />Source:System.ServiceModel
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: