Is it necessary to Dispose() when using a custom S

2019-08-10 12:33发布

问题:

Is it necessary to Dispose() when using a custom ServiceHostFactory?

In my WCF .svc file I have defined a custom Factory as: <%@ ServiceHost Factory="Service.ServiceHostFactory" %>

It appears that a Dispose() is not being called since the overridden CreateServiceHost() method is not being called at each execution of the application calling the service. (Also, among other things, logging is not being performed after each call and the trace.xml file I generated says that it is in use by another process).

I do have the service decorated with [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] so I expect something else is going on that I'm not aware of. In the client application where the instance to the service is created I am Dispose()'ing of the reference via a finally block but is it necessary to perform a similar operation in the Factory on the server side?

    Finally
        service.Dispose()
    End Try

Thanks

回答1:

The service host factory returns a service host, not an instance of the service class. The factory is usually called only once per activation of the service, and the host it returns is used until the IIS application pool is recycled. The service instance is handled by an IInstanceProvider, not the service host (although as you're creating the host you can change the instance provider if you want to dispose the service instance - for more information about instance providers, see http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/31/wcf-extensibility-iinstanceprovider.aspx and http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.aspx).

So in short, you should not dispose the service (or is it the host?) which you're returning from the service host factory. If you want to handle service disposal, you should implement your own instance provider.