我应该在哪里清理 ServiceHost 的私有资源?

Where should I cleanup private resources for a ServiceHost?

我已经设置了一对 WCF NamedPipes Server/Client 应用程序,但是当主机停止并调用 ServiceHost.Close() 时,它似乎没有适当地清理创建主机的对象(使用对象而不是类型来实例化主机)。

服务端应用代码如下:

static void Main(string[] args) {
  // Specify the device type. Consider command line arguments here.
  DeviceTypes deviceType = DeviceTypes.myDeviceType;

  // Create the service object.
  ServiceHost selfHost = ServiceFactory.CreateService(deviceType);
  try {
    // Start the service.
    selfHost.Open();
    System.Console.WriteLine("The service is ready.");
    System.Console.WriteLine("Press <ENTER> to terminate service.");
    System.Console.WriteLine();
    System.Console.ReadLine();

    // Stop the service.
    System.Console.WriteLine("Closing the service.");
    selfHost.Close();
  } catch (CommunicationException e) {
    System.Console.WriteLine("An exception occurred: {0}", e.Message);
    selfHost.Abort();
  }
}

ServiceFactory.CreateService方法:

public static ServiceHost CreateService(DeviceTypes type) {
  // Create the client object.
  // Create_Server only creates an uninitialized child class based on the type.
  IMyServer client = MyServerFactory.Create_Server(type);

  // Initialize the client.
  client.Initialize();

  // Create the service object.
  MyService server = new MyService(client);

  // Create a service host.
  ServiceHost selfHost = new ServiceHost(server, new System.Uri(baseAddress));

  // Add a service endpoint.
  selfHost.AddServiceEndpoint(typeof(IMyActions), new NetNamedPipeBinding(), relAddress);
  return selfHost;
}

MyServiceclass(包含我要清理的资源):

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = 
InstanceContextMode.Single)]
class MyService : IMyActions
{
    private IMyServer server;

    public MyService(IMyServer server) {
        this.server = server;
    }

    // Bunch of public operations to carry out the contract
    public bool Initialize() {
        return server.Initialize();
    }

    public void Dispose() {
        server.Dispose();
    }

    // No-op to check pipe connection.
    public void ConfirmConnection() { }
}

MyService class 中的 server.Dispose() 方法应该如何以及在何处调用? 我认为这将由 selfHost.Close() 处理,但似乎不是...

您的输出是 ServiceHost,这不是您创建的自定义类型。 因此它不会自动调用 IMyServer.Dispose().

而不是 returning ServiceHost,创建某种类型的适配器来管理 ServiceHost 和您的 IMyServer 实例并将其 return void Main() 方法。

然后,只需添加一个 finally 子句(或实现 IDisposable 并使用 using)并调用适配器的处置,这将调用 serviceHost.Dispose()myServer.Dispose()