WCF, Unity: Teardown disposable instances - wcf

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)

Related

Ninject: What happens to non-disposable InRequestScope and InTransientScope objects after the HTTP request is finished?

I have searched a lot about these question, here and a lot of other places, but not getting everything I want to know!
From a WebApi project point-of-view, when are InTransientScope objects Created? In the Ninject docs it is stated that such objects are created whenever requested, but in a web api project that handles HTTP requests, the instance is created at the request start time so in this regard it is the same as InRequestScope then?
In a WebApi project, is it okay to use InTransientScope objects knowing that they will never be kept track of by Ninject? If Ninject never keeps track of Transient objects, then what is the purpose of this scope and what happens to such objects after they have been used?
If I declare an object with InRequestScope and that object doesn't implement the IDisposable interface, what happens to such object after the web request has completed? Will it be treated the same way as an InTransientScope object?
Are different scopes to be used for: WebApi controllers, Repositories(that use a InRequestScope Session that is created separately) and Application services?
There's two purposes for scopes:
Only allow one object to be created per scope
(optionally) dispose of the object once the scope ends.
As said, the disposal is optional. If it doesn't implement the IDisposable interface it's not being disposed. There's plenty of usecases for that.
The InTransientScope is the default scope - the one being used if you don't specify another one. It means that every time a type A is requested from the kernel one activation takes place and the result is returned. The activation logic is specified by the binding part that follows immediately after the Bind part (To<...>, ToMethod(...),...).
However, this is not necessarily at the time the web-request starts and the controller is instanciated. For example, you can use factories or service location (p.Ex. ResolutionRoot.Get<Foo>()) to create more objects after the controller has been created. To answer your questions in short:
When: When a request takes place or whenever your code asks for a type from Ninject either directly (IResolutionRoot.Get(..)) or through a factory. As InTransientScope objects are not being tracked they will not be disposed, however, if they are not disposable and the entire request code requests only one IFoo then practically there's is no discernible difference (apart from the slight performance hit due totracking InRequestScope()-ed objects)
As long as you don't need to make sure that instances are shared and/or disposed this is completely fine. After they are not being used anymore, they will get garbage-collected like any object you would new yourself.
When the scope ends ninject will remove the weak reference to the non-IDisposable object. The object itself will not be touched - just like when bound InTransientScope()
That depends on your specific requirements and implementation details. Generally one needs to make sure that long-scoped objects don't depend on short-scoped objects. For example, a Singleton-Service should not depend on a Request-scoped object. As a baserule, everything should be InTransientScope() unless there's a specific reason why it should not be. The reason will dictate what scope to use...

Context and Instance in WCF

I am reading Juval Löwy's Programming WCF Sevices. It mentions:
In WCF, we have Context in which we have the instance. By default, the lifetime of the context is the same as that of the instance it hosts. We can have separate lifetimes for both.
WCF also allows a context to exist without an associated instance at all.
Why would we release the instance and keep the context empty?
Coincidentally I recently read the chapter you're probably referring to. In his book Löwy explains why this may be useful. First he writes:
WCF also allows a context to exist without an associated instance at all. I call this instance management technique context deactivation.
After mentioning this is typically done using an OperationBehavior with a specific ReleaseInstanceMode, he goes on and hints on when you could use this:
You typically apply instance deactivation on some but not all service methods, or with different values on different methods. [...] The reason you typically apply it sporadically is that if you were to apply it uniformly, you would end up with a per-call-like service, in which case you might as well have configured the service as per-call.
So you can use this "deactivation" to ensure only certain methods in a service with sessions behave as if they were part of a per-call service. The abovementioned MSDN article also explains this, in a different wording:
Use the ReleaseInstanceMode property to specify when WCF recycles a service object in the course of executing a method. The default behavior is to recycle a service object according to the InstanceContextMode value. Setting the ReleaseInstanceMode property changes that default behavior. In transaction scenarios, the ReleaseInstanceMode property is often used to ensure that old data associated with the service object is cleaned up prior to processing a method call.
Disconnecting the context from the instance makes sense when:
Instance creation is customized/extended. For example if you are creating your service instance with a custom IInstanceProvider with a dependency injection library (for example Unity) you might want a Unity lifetime manager to handle the service instance lifetime.
Some but not all operations result in an expensive service instance to be invalidated. For example: The service object loads a large expense resource as a part of creation. If the service operations called by the client modify or invalidate the resource, it needs to be disposed and reloaded for the next caller. If the operations don’t invalidate the resource the service instance can be reused by the next caller. (In almost all cases there’s a better way to solve this problem, but WCF allows it).
I’m sure there are additional use cases.

Passing client context using Unity in WCF service application

I have a WCF service application (actually, it uses WCF Web API preview 5) that intercepts each request and extracts several header values passed from the client. The idea is that the 'interceptor' will extract these values and setup a ClientContext object that is then globally available within the application for the duration of the request. The server is stateless, so the context is per-call.
My problem is that the application uses IoC (Unity) for dependency injection so there is no use of singleton's, etc. Any class that needs to use the context receives it via DI.
So, how do I 'dynamically' create a new context object for each request and make sure that it is used by the container for the duration of that request? I also need to be sure that it is completely thread-safe in that each request is truly using the correct instance.
UPDATE
So I realize as I look into the suggestions below that part of my problem is encapsulation. The idea is that the interface used for the context (IClientContext) contains only read-only properties so that the rest of the application code doesn't have the ability to make changes. (And in a team development environment, if the code allows it, someone will inevitably do it.)
As a result, in my message handler that intercepts the request, I can get an instance of the type implementing the interface from the container but I can't make use of it. I still want to only expose a read-only interface to all other code but need a way to set the property values. Any ideas?
I'm considering implementing two interfaces, one that provides read-only access and one that allows me to initialize the instance. Or casting the resolved object to a type that allows me to set the values. Unfortunately, this isn't fool-proof either but unless someone has a better idea, it might be the best I can do.
Read Andrew Oakley's Blog on WCF specific lifetime managers. He creates a UnityOperationContextLifetimeManager:
we came up with the idea to build a Unity lifetime manager tied to
WCF's OperationContext. That way, our container objects would live
only for the lifetime of the request...
Configure your context class with that lifetime manager and then just resolve it. It should give you an "operation singleton".
Sounds like you need a Unity LifetimeManager. See this SO question or this MSDN article.

Not disposing of a WCF proxy?

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.

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