• 推荐
  • 评论
  • 收藏

WCF服务重构实录(下)

2022-11-16    510次浏览

前两篇写了在IIS7下部署SVC文件引导WCF服务,采用了net.tcp文件,但是实际的开发中,由于项目的架构已经确定,不宜做大的改动,且为了试项目组成员开发方便,我们之前的项目架构是这样的:

image

主体是WebHost,这是用来托管WCF服务的,放弃了ConsoleHost,那么现在的问题是能不能仅仅通过配置文件来托管服务,不必通过SVC文件的连接呢,MSDN上给出了一个很好的解决方案:http://msdn.microsoft.com/zh-cn/library/ee816902(en-us,VS.100).aspx

主要使用的是一个配置元素<serviceActivations>,MSDN给出的说明是:

一个配置元素,用于添加可定义虚拟服务激活设置(映射到 Windows Communication Foundation (WCF) 服务类型)的设置。使用此配置元素可以在不使用 .svc 文件的情况下激活承载在 WAS/IIS 中的服务。

主要语法是:

<servicehostingenvironment>
   <serviceactivations>
      <add service="String" factory="String">
   </add></serviceactivations>
</servicehostingenvironment>

那么有了这个好组件,我们就拿来改造现有的服务吧。

首先,之前的服务配置是

<services>
      <service name="WCFLib.Add" behaviorconfiguration="MyBehavior">
        <endpoint bindingconfiguration="netTcpBindConfig" contract="WCFLib.IAdd" binding="netTcpBinding" address=""></endpoint>
        <endpoint contract="IMetadataExchange" binding="mexTcpBinding" address="mex"></endpoint>
      </service>
    </services>

我们为这个配置增加服务激活配置

<servicehostingenvironment>
      <serviceactivations>
        <add service="WCFLib.Add" relativeaddress="NewAddService.svc">
      </add></serviceactivations>
    </servicehostingenvironment>

来看一下现在完整的配置

<system.servicemodel>
    <bindings>
      <nettcpbinding>
        <binding name="netTcpBindConfig">
          <security mode="None">
            <transport protectionlevel="EncryptAndSign" clientcredentialtype="Windows">
            <message clientcredentialtype="Windows">
          </message></transport></security>
        </binding>
      </nettcpbinding>
    </bindings>
    <servicehostingenvironment>
      <serviceactivations>
        <add service="WCFLib.Add" relativeaddress="NewAddService.svc">
      </add></serviceactivations>
    </servicehostingenvironment>
    <services>
      <service name="WCFLib.Add" behaviorconfiguration="MyBehavior">
        <endpoint bindingconfiguration="netTcpBindConfig" contract="WCFLib.IAdd" binding="netTcpBinding" address=""></endpoint>
        <endpoint contract="IMetadataExchange" binding="mexTcpBinding" address="mex"></endpoint>
      </service>
    </services>
    <behaviors>
      <servicebehaviors>
        <behavior name="MyBehavior">
          <servicethrottling maxconcurrentsessions="1000" maxconcurrentinstances="1000" maxconcurrentcalls="1000">
          <servicemetadata httpgetenabled="true">
          <servicedebug includeexceptiondetailinfaults="true">
          <datacontractserializer maxitemsinobjectgraph="6553600">
        </datacontractserializer></servicedebug></servicemetadata></servicethrottling></behavior>
      </servicebehaviors>
    </behaviors>
  </system.servicemodel>

删除SVC文件后的目录是这样的

image

那么怎么使用这个没有SVC文件的WCF服务呢,很简单,我们只要认为有这个服务就可以了,删除之前的Client中的引用,我们重新添加引用一下

image

再运行一下试试看

image

原文地址:https://www.cnblogs.com/Leo_wl/p/2007675.html