WCF服务的寄宿方式
WCF寄宿方式是一种非常灵活的操作,可以寄宿在各种进程之中,常见的寄宿有:
IIS服务、Windows服务、Winform程序、控制台程序中进行寄宿,从而实现WCF服务的运行,为调用者方便、高效提供服务调用。
签名
前面介绍过了WCF常用的一种寄宿方式,IIS服务寄宿。这种寄宿方式是最为方便的方式,而且由于服务只需要IIS运行就能自动运行起来,因此广为使用。 创建这种方式IIS寄宿方式的,只需要在解决方案里面,添加WCF服务应用程序,就可以生成这种的服务模块了。
将WCF服务寄宿到其他进程之中:(如控制台应用程序)
1.新建解决方案:添加WCF服务库项目。
修改里面生产的配置项:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<!-- 部署服务库项目时,必须将配置文件的内容添加到
主机的 app.config 文件中。System.Configuration 不支持库的配置文件。 -->
<system.serviceModel>
<services>
<service name="WcfService.Library1.Service1">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:20002/Design_Time_Addresses/WcfService.Library1/Service1/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- 除非完全限定,否则地址将与上面提供的基址相关 -->
<endpoint address="WcfService.Library1.Service1" binding="basicHttpBinding" contract="WcfService.Library1.IService1">
<!--
部署时,应删除或替换下列标识元素,以反映
用来运行所部署服务的标识。删除之后,WCF 将
自动推断相应标识。
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- 元数据交换终结点供相应的服务用于向客户端做自我介绍。 -->
<!-- 此终结点不使用安全绑定,应在部署前确保其安全或将其删除 -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- 为避免泄漏元数据信息,
请在部署前将以下值设置为 false -->
<serviceMetadata httpGetEnabled="True"/>
<!-- 要接收故障异常详细信息以进行调试,
请将以下值设置为 true。在部署前设置为 false
以避免泄漏异常信息 -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
添加控制台应用程序,引入WcfService.Library1的引用,添加using System.ServiceModel;库文件引用。将WcfService.Library1中的App.config复制到控制台应用下面。修改属性为始终复制。
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using WcfService.Library1;
namespace WcfTest.Demo2
{
class Program
{
static void Main(string[] args)
{
CoreConfigOpen();
}
/// <summary>
/// 通过加成配置App.config开启WCF服务
/// </summary>
static void CoreConfigOpen()
{
try
{
ServiceHost selfHost = new ServiceHost(typeof(WcfService.Library1.Service1));
selfHost.Open();
Console.WriteLine("寄宿到控制台应用程序,通过加载App.Config开启WCF服务");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("CoreCodeOpen Error:" + ex.Message);
}
}
}
}
生成后以管理员身份直接运行项目。
在浏览器地址栏输入:配置文件里的baseAddress的url.
可以看到服务寄宿成功,就可以根据上面的链接进行服务引用和开发。这样就简单的实现了控制台应用程序的寄宿。windows服务和其他进程的寄宿也类似如此。上面是根据配置文件中的配置项进行寄宿,还可以以纯代码的方式实现在其他进程中的寄宿。