This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page.
Moving down to the list of the extensibility points, the IInstanceProvider is actually quite useful when you have a service class which needs some initialization data. In most of the WCF service examples I’ve seen in the web, they’re simple classes, almost self-contained, which didn’t have any external dependencies. The default instancing behavior for WCF (simply call the parameter-less constructor for the service class) works perfectly in those cases. However, there are quite a few scenarios where this is not the case – the service depends on some database, the service class needs to listen to some external events, or we want to initialize the service class with a different parameter depending on the situation where it’s being used (or even on the incoming message which is being sent to it) – and the instance provider interface is the hook that the WCF extensibility provides to allow us total control over the instantiation of the service class. Another scenario where this may be useful is that if the service class only has a default constructor, but it does some heavy initialization, so you may want to create a pool of service instances – the instance provider can help in this case as well.
None. As with most runtime extensibility points, there are no public implementations in WCF. There are many internal implementations, such as the default System.ServiceModel.Dispatcher.InstanceProvider, which uses the default constructor for the service type to create the instances.
The IInstanceProvider has two overloads of the GetInstance method used to create a new instance of the service class. The first one receives only an InstanceContext object, while the second one also receives an instance of the Message object which represents the request which is going to be sent to the service. In practice, the first one is seldom invoked – I could find in Reflector some code paths which called that one, but I couldn’t actually make a service in which that method was invoked after trying for about 30 minutes. It’s possible that it is invoked by some obscure code path, so if you’re implementing a custom one, and on the GetInstance(InstanceContext) you simply delegate the call to the other overload passing a null message, it’s nice to have the code consider that the message may in fact be null.
The need for a new instance of the service class depends on the instancing mode of the service. For services with the PerCall mode, a new service instance (with a call to GetInstance) will be created for every new request coming from the client; for PerSession services, whenever a request which creates a session new session arrives, a new service instance is created, but subsequent requests for the same session will continue using the same service instance (if the binding does not support sessions, then a PerSession instance context mode becomes PerCall). Services with InstanceContextMode.Single actually do not use the instance provider – the service instances must be passed to the service host constructor, or the service class needs to have a parameter-less constructor which will be used to create the singleton instance.
When the WCF runtime is done with the service object, it will call ReleaseInstance on the provider, which can be useful if the service class has some dependencies which it needs to dispose of, or in a pooling scenario, where the code can then return that service instance to the pool of available instances.
Instance providers only apply at the server side, and they’re bound to the endpoint dispatcher, and available at the DispatchRuntime object. They’re typically defined as either service or endpoint behaviors, as in the example below.
Among the usage examples for instance providers, one which is quite interesting is to be able to test WCF service classes which have dependencies to external components, such as databases. Outside of the WCF world, the way this is usually done is by using some sort of IoC / factory framework which manages the dependency based on some creation rules. That dependency is often represented as an interface which is passed to the service class constructor, so that it can be mocked with a test implementation during test time. In the example below I’ll implement a very simple factory method for such dependency, so that the service can be tested both inside the WCF pipeline and outside of it.
And before starting with the code, the usual disclaimer: this is a sample for illustrating the topic of this post, this is not production-ready code. I tested it for a few contracts and it worked, but I cannot guarantee that it will work for all scenarios (please let me know if you find a bug or something missing). Also, it does take many shortcuts for simplicity sake, such as using a file-based “database”, a very simple IoC container (don’t use it in production), it doesn’t add a lot of error checking, and it definitely does not have even a minimum number of tests to make us claim that the service is “tested”.
The service is a simple pricing service. You add items to a “shopping cart”, and at the end you can “checkout”, where you get the price (and in this simplified example, the cart is emptied). Here are the data contracts used in this service:
The service interface will use a session to store the items in the cart, so the service contract will require a binding which supports such sessions.
The product repository interface I’ll use in this example is a very simple one, with a single operation which returns product instance via its ID.
Now the service class. As I mentioned before, it has a dependency on a product repository interface, which needs to be passed at construction time. The service is decorated with the [InstanceProviderBehavior] interface, which is the service behavior which we’ll use to define the instance provider for this service. Since we’re using a session, we can store the cart as an instance variable for the service class.
With this definition we actually can start writing some unit tests for the pricing service class, completely outside of WCF:
Back to the service code. Since the service does not have a parameter-less constructor, setting the instance provider is required – otherwise there would be a validation error when opening the service. The provider is implemented using a product repository factory (a very, very simple IoC container).
The provider is plugged in to the WCF pipeline by using the InstanceProviderBehaviorAttribute class, first shown in the service definition
And with this behavior, we can start testing the service inside the WCF stack (I wouldn’t dare to call it unit test, WCF is well-known for being unit-test-unfriendly).
And when we’re happy with the tests, we can finally hook it up with the “real” product repository. For this example I’m using a file-based “database”, but in a more realistic scenario we’d retrieve the products from the inventory database.
And that’s it. WCF has a (well-deserved, unfortunately) reputation for not being very unit-testable, but there are some improvements we can make, and the instance provider is one way of improving the testability of WCF services.
I’ll stop following the order listed in the table of contents, and start jumping around to cover the extensibility points which are used more often. Next: error handlers.
[Code in this post]
[Back to the index]