Not disposing of a WCF proxy? - wcf

I have a WCF service which is a singleton and which manages a collection of proxies to another WCF service which is session-based. The singleton creates a new proxy and passes it some work to do, and the session-based service makes calls back to the singleton service when certain activities complete (pretty much all of the OperationContract methods are one-way). The typical completion path is that the singleton receives an event from a hardware device when the process is complete, and it calls a method on the session-based service which returns the final status, and then disposes of its proxy. When an error situation is encountered and the session-based service can't continue with what it needs to do, I need to make a call back to the singleton to let it know to dispose of the proxy associated with that instance. However, to make the WCF method call back to the singleton, I need to create a proxy back to the singleton. What I'm seeing happen is that the singleton disposes of its proxy as expected, but every time the proxy to the singleton that the session-based service created times out when I try to dispose of it. Since the session ends with that method call and the instance will be disposed of, does it matter if the proxy it created doesn't get properly disposed?

Disposing of a WCF service is not the same as disposing of any other object that implements IDisposable. It is ok to dispose of the service when it is in a good state but when a fault occurs the dispose method will throw another exception.
Some insight is here and perhaps use the WCFProxyGenerator but I have not tried it
Not sure exactly the problem with the session based service and whether it is different from the WCF service.
My recommendation is not to use a singleton but use Dependency Injection to give the class that uses the WCF service a factory so when it wants the service it can create it. And when a fault occurs it can throw away the old and create a new one. Without seeing some code it is hard to see if this is possible.

Related

Force a client to call a method on the service?

I'm wondering if there's any way to force a client to call a specific method on a duplex WCF service. My situation is this, my service implementation is going to keep a collection of subscribers. The problem with this approach is, what if the client doesn't call Subscribe()? I was thinking that in my client interface, I'd have a method called Subscribe, but that doesn't get me anywhere since the code to actually call the service can still be left out of the implementation. Is this possible?
Thanks!
Duplex WCF service uses WCF session so you can mark your Subscribe method with:
[OperationContract(IsInitiating=true)]
void Subscribe();
All other methods will have IsInitiating=false and because of that Subscribe method will have to be the first method called to start a new session. You can also have special method with IsTerminating=true to close the session.

WCF, Unity: Teardown disposable instances

we've set up a WCF service which uses a Unity Container to resolve instances for managing Exchange 2010 Powershell commands. We defined an IExchangePowershell interface which has a concrete implementation that implements IDisposable. After some time we encountered the problem that we couldnt execute powershell commands anymore since the server said there are already too many powershell sessions open. It seems that we never really disposed of our powershell instances. The Dispose() method of the concrete Powershell would take care of closing the runspace and the session. Once I call this in the repository methods, we don't get the errors anymore.
((IDisposable)this.powershell).Dispose();
Now of course I dont want to explicitly call dispose in every repository method. I thought unity could take care of this. Our WCF Instance Provider does this:
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
container.Teardown(instance);
}
But that doesnt really dispose of the IExchangePowershell instances. Do you have any idea how I could automatically dispose of those instances?
That is actually well known problem in Unity. TearDown method does nothing. If you want to use TearDown you must create custom container extension.
I wrote an article about using object lifetimes managers in Unity and their impact on disposing. If you use default TransientLifetimeManager or PerResolveLifetimeManager the Unity will even don't track existence of your objects so it can't call Dispose. The only lifetime managers which calls Dispose on resolved instances are ContainerControlledLifetimeManager (aka singleton) and HierarchicalLifetimeManager. The Dispose is called when the lifetime manager is disposed.
The solution for you is either use casting and handle Dispose manually as you already did or switch to HiearchicalLifetimeManager and create new subcontainer for each incoming WCF request. Each subcontainer will only handle single request and it will dispose resolved entities with hiearchical lifetime.
There are other ways, for example this article builds a very complex code around Unity to support disposing and TearDown for all resolved objects.
The answer depends on how you register your type / instance with unity. Standard implementation of Teardown does nothing at all.
If you register type then Unity does not store reference to instance it creates - it's up to you to manage it's lifetime and dispose it. If you register instance, then the instance lifetime is managed by unity and is kept until you dispose of the container.
The link below helps to understand a bit better about lifetime management:
http://msdn.microsoft.com/en-us/library/ff648098.aspx
You need to ask yourself when you would like your objects to be disposed. If you know when to call ReleaseInstance, you might as well call IDispose instead of it.
(I'm sorry, I'm not familiar with WCF, so I'm not sure what instance provide is in this context)

how to create and manage wcf service clients?

At first I treated them as any dependency passing them in the ctor to the class consuming the service:
var serviceConsumer = new ServiceConsumer(new MailingServiceClient())
The problem was that once an exception was thrown from the service it entered a faulted state and would not reply to any requests, so re-initialization was due.
Further more, I became familiar with the fact that wcf services may not be disposed properly on several occasions, because the dispose method of the generated proxy is broken (calls close without checking the fault state) and encountered a couple of ways to overcome that:
wrapping every call to every service.
override the default IDisposable behavior of the scvutil.exe-generated class
Since I wouldn't like the consumer code to create the service client himself for testing reasons, my questions are:
how can I maintain a working un-faulted service?
how can I still use dependency injection for testability?
Found a nice solution.
a proxy generator that replaces the VS one, and generates a wrapper around the default proxy that deals with proxy faults, timeouts, and correct disposal.
http://wcfproxygenerator.codeplex.com/
seems to be working fine for me.

How to dispose WCF services correctly?

My WCF service is IDisposable because it uses a ReadWriterLockSlim. When I dispose both of them in the following method:
public void Dispose()
{
lockSlim.Dispose();
}
Some of the public methods are still running (or accepting new connections, I don't know), and it fires exceptions because of the attempts of using disposed objects (the lockSlim in this case). It would be nicer if, when stopping a Windows Service hosted WCF Service, the Dispose method was called after stopping all running methods and closing it for new connections. But it seems that it must be done manually. There are any shortcuts or examples?
I think there is no need to dispose LockSlim object. On service stop, call ServiceHost.Close() . all the threads will interrupr its work, all the links will be broken and Garbage colector will take care about the memory. ReadWriterLockSlim is not critical resource. Please let me know if it was helpfull

WCF OperationContext

I'm developing a WCF service and if there is an error I want to serialize the incoming parameter from the original method that was called on the service. I am using IErrorHandler to catch all exceptions.
My initial thoughts were that I will store the serialized parameter in OperationContext.IncomingMessageProperties so that I can access it from the HandleError method. However, as this isn't run on the original thread I believe the OperationContext will be null, so I am considering accessing it from the ProvideFault method.
Does this seem feasible? And will it work with OneWay service calls?
Not sure I can really help you much here, but let me try:
on your client, your code basically calls a method and passes it parameters. The WCF stack on the client side then converts that into a SOAP message (typically with an XML body, but could be binary, too) with headers and all and then sends that message across the wire to the server to be processed.
The server then attempts to deserialize that message into an object and attempts to call a message on a server implementation object. That method on the server object will most likely have the same parameters again, as the client - however, there's a possibility that the call will fail before that method even gets called.
So what I'm trying to say is: you can't rely on the fact that your server-side method with its parameters really gets called - there might have been a problem with e.g. authentication, the message format, a missing header or something else, that causes the server side to fail and throw an exception even before the server-side method ever gets called.
In the end, in the IErrorHandler, there's no way I would know of to get a hold of the message and/or the method and its parameters - all you can get are the error that occured on the server, and you can use that to turn it into a SOAP fault.
What you could do - both on the client and the server side - is create a new behavior that plugs into the WCF stack, and that records the methods being called and the parameters being passed into them - by implementing a class that implements the IParameterInspector interface of WCF. But that only will get called if the message on the client and the server will get properly deserialized and the server-side method really gets called.
Check out some of these links for more info on WCF extensibility:
How to: Inspect or Modify Parameters
WCF Extensibility: Parameter Inspectors
IParameterInspector in WCF
Extending WCF with custom behaviors
Hope this helps a bit!
Marc