为什么服务没有启动?

Why doesn't the service start?

我正在尝试启动自托管服务,所以过程是这样的:

问题是 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项目的代码bihind:

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

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

    private ServiceHost _host;
}

为什么服务没有启动?

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

您应该在释放表单实例时手动释放 ServiceHost 实例。

    public MainWindow()
    {
        InitializeComponent();

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

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