服务为什么不启动?

时间:2019-02-10 12:48:12

标签: c# wcf

我正在尝试启动自托管服务,因此过程如下:

  • 使用VS2017的WCF模板,我使用服务和合同创建了一个库。
  • 我创建一个新的WPF项目,该项目引用该库以使用该服务。该WPF应用程序将托管服务。

  • 我将使用VS2017模板创建的库的app.config中的所有配置复制到WPF应用程序的app.config中。我只是修改了URL,为避免冲突,URL将是Service2而不是Service1。这是因为如果我开始调试,Visual Studio将启动库服务和WPF应用程序服务。

问题是WPF应用程序中托管的服务未启动。另外,我尝试卸载库项目以仅运行WPF项目,以避免启动我不想运行的服务,但是问题是相同的,该服务未启动。

app.config是这样的:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="Servicio.Service1">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8733/Design_Time_Addresses/Servicio/Service2/" />
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="Servicio.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

我的WPF项目的代码如下:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        using (_host = new ServiceHost(typeof(Servicio.Service1)))
        {
            _host.Open();
        }
    }

    private ServiceHost _host;
}

为什么服务没有启动?

1 个答案:

答案 0 :(得分:1)

好吧,您正在创建一个主机,将其打开,然后由于using语句而立即将其处置。所以这是预期的行为。

处置表单实例后,应手动处置ServiceHost实例。

    public MainWindow()
    {
        InitializeComponent();

        _host = new ServiceHost(typeof(Servicio.Service1)))
        _host.Open();
    }

然后,您可以在处置表单时使用_host.Dispose();处置主机。

相关问题