如何在托管Windows服务中托管WCF服务?

时间:2013-08-30 23:02:14

标签: c# asp.net wcf windows-services

我的解决方案中有3个项目。

  • 测试客户端=>用于通过tcp ip添加引用和访问
  • WcfServiceLibruary1 =>执行我的methots
  • WindowsService1 =>用于安装和运行Windows服务(帐户:网络服务,StartType:自动)

enter image description here

我在msdn示例中使用了所有相同的代码

http://msdn.microsoft.com/en-us/library/ff649818.aspx

我使用的是一个有2个methot的wcf服务。我想在托管的windows服务中使用这个wcf服务。我在我的解决方案中添加了一个windows服务并设置了引用。

我在wcf-app.config上使用此地址referance:

net.tcp://localhost:2023/Service1

现在的问题是:

我成功使用

添加对我的测试客户端项目的引用

net.tcp://localhost:2023/Service1

但是这个referance地址不能在安装时用作windows服务! 当我将其安装为Windows服务时,我无法访问此地址, 我收到了这个错误:No connection could be made because the target machine actively refused it

WcfServiceLibruary app.config:

<?xml version="1.0"?>
  <configuration>
    <system.web>
    <compilation debug="true"/>
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="WcfServiceLibrary1.Service1">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration="" contract="WcfServiceLibrary1.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:2023/Service1"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="false"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

我的WindowsService:

protected override void OnStart(string[] args)
{
    if (myServiceHost != null)
    {
        myServiceHost.Close();
    }
    myServiceHost = new ServiceHost(typeof(Service1));
    myServiceHost.Open();
 }

当我在visualstudio服务主机上启动时,一切正常: enter image description here

1 个答案:

答案 0 :(得分:2)

阅读本文

在此构建服务并提供托管代码

http://msdn.microsoft.com/en-us/library/ms733069.aspx

相关问题