Best Practice for WCF Service Proxy lifetime? - wcf

When working with WCF services, is it better to create a new instance of the service every time you use it? Or is it better to create one and re-use it? Why is either approach better? Is it the same for asynchronous proxies?

Or is it better to create one and re-use it?
Do not start to implement your own pooling implementation. That has already been done in the framework. A WCF proxy uses cached channels factories underneath. Therefore, creating new proxies is not overly expensive (but see Guy Starbuck's reply regarding sessions and security!).
Also be aware that a proxy times out after a certain idle time (10mins by default).
If you want more explicit control you might consider using ChannelFactories and channels directly instead of the "easy to go, full out of the box" ClientBase proxies.
http://msdn.microsoft.com/en-us/library/ms734681.aspx
And a "must read" regarding this topic is:
http://blogs.msdn.com/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx

in addition to the things Guy Starbuck mentioned a key factor would be the security model you're using (in conjunction with the session requirements) - if you don't re-use your proxy, you can't re-use a security sessions.
This means that the client would have to authenticate itself with each call which is wasteful.
If, however, you decide this is what you wish to do, make sure to configure the client to not establish a security context (as you will never use it), this will save you a couple of roundtrips to the server :-)

One more point to consider is channel faults. By design WCF does not allow to use client proxy after unhandled exception happened.
IMyContract proxy = new MyContractClient( );
try
{
proxy.MyMethod( );
}
catch
{}
//Throws CommunicationObjectFaultedException
proxy.MyMethod( );

There is a corollary here to Server Activated Objects in .NET Remoting (one of the technologies that is replaced by WCF), which have two modes, "Single Call" (stateless) and "Singleton" (stateful).
The approach you take in WCF should be based on your performance and scaling requirements in conjunction with the needs of your consumers, as well as server-side design constraints.
If you have to maintain state between calls to the service, then you will obviously want to have a stateful instance, but if you don't you should probably implement it so that it is static, which should scale better (you can more easily load balance, etc).

Related

WCF as BLL (Middle Tier) and Security techniques

So bear with me, i am new at MVC and WCF. I already have a set of services (WCF) that exposes my BLL and I am trying to consume those from my MVC.net web application but i am unsure on how to perform security operations here.
These are my app requirements:
Be able to consume WCF services using different credentials for every user on the web application
My BLL (WCF) needs to know what consumer is calling it (right now I only have the MVC app but i am planning to add iOS and Andriod calls to it, so later on i will add REST services to the WCF endpoints) Is there any design pattern for this out there? (or should i just use the soap header to include the caller ID? should i use some sort of caller secret or something?)
I need a security mechanism like Tokens or something so I dont have to pass the username and password on every call of the service method (WCF)
What i have so far:
WCF uses a certificate and and with a custom username validator.
I have manually coded proxies using the contract interfaces instead of generated proxies: But I hate the fact that i have to validate username and password every time a call is made to a WCF service. How in heaven can i use Tokens here? like to know if a given token sent on the soap header is valid or not yet expired? i have searched a lot and no tutorial/code/example is clear enough for me to actually start coding that ;(
I am trying to cache the ChannelFactory but should I? i mean, i will need to cache a channer factory per logged in user per contract ;( is that ok? what can i do here?
Thanks in advance!
Should you cache the ChannelFactory per user per contract?
It depends. There are a couple of considerations. Instantiating a channel factory could take up to 70ms. If you are doing this repeatedly, you will see a noticeable performance hit if you are not caching the ChannelFactory and instantiating one (or more) each time a user makes a http request to your MVC app that results in controller actions calling web services. This would indicate that caching the channelFactory would be beneficial for speed.
On the other hand, depending on the number of users you have, if you are caching a lot of channel factories (in a static dictionary for example), you are going to start to use a non-trivial amount of memory - this may become an issue for you.
You have to decide if the cost of instantiating channel factories on the fly (and correctly closing / aborting them and their contained channels) is too high a price vs increasing memory utilisation in the application pool hosting your MVC app.
Either way, I strongly advise to profile your app before you deploy to production.

Dispatcher/Proxy (Client) Extensions for better throughput of WCF service

Need some expert opinion on this case study.
Problem Statement/Scenario:
My WCF client/proxy continually requiring some lockup data from relevant WCF service. More precisely, I've a WCF service that provides Location data (City/Country etc) from a database (although data is cached on Service). Some how I want to avoid Serialization/DeSerialization (Object contains a lot of associated properties as well as inner objects) cost and service operation execution for better throughput.
Few days back I studied WCF behaviors/WCF extension methods.I found an interesting article on MSDN (http://msdn.microsoft.com/en-us/magazine/cc163302.aspx). After reading this article I thought this could help me to improve performance of my service. So before implementing this I want to confirm that either I'm thinking in right direction or any other solution can solve my problem.
I'm thinking to implement Dispatcher Extensions to solve this problem instead of Proxy (Client) Extensions. I've following queries?
I) Where (Proxy/Service level) I need to implement extensions?
II) When implementing Dispatcher Extensions my call will not send to actual service and I'll save Serialization/DeSerialization cost. Right/Wrong?
III) Implementing Dispatcher Extensions in my case is also better, because why need not to bother about which proxy interface method call occurred as caching logic is on service side. Right/Wrong?
Please suggest me a better solution as I want to save Serialization/DeSerialization cost as well as I want to implement data caching.
Thanks in advance
/Rizwan
There are two ways I've incorporated WCF caching in the past:
Using Castle DynamicProxy to generate proxies for my ServiceContract interfaces. These dynamic proxies use interceptors to perform caching. If the data is not in the cache, the interceptor creates a real WCF client (a ChannelFactory<TInterface>) and invokes the WCF operation, then caches the result. I like this approach, because the caching implementation isn't really WCF specific.
Implement an IRealProxy for WCF which wraps the actual remote operations and performs caching/retrieval as necessary. In principal, this is similar to approach 1, but the implementation is specific to WCF (with remnants of .NET Remoting). I used this approach before migrating to #1. I migrated to approach 1 because approach 1 let me accomplish caching on both the client and the server in an implementation agnostic manner. At the time, I rolled my own RealProxy, but it looks like someone else has since done the same and posted the code: http://blog.ngommans.ca/index.php?/archives/31-Custom-Proxy-Generation-using-RealProxy.html

Things to consider while calling one WCF service from another

We are migrating set of WSE services to WCF platform.
The new WCF services are called over secured HTTP. (https)
I want to invoke an operation contract of one WCF service from another. Both the services are mostly hosted in the same IIS, but they can be on separate IIS server.
Do I need to take care of some things (which i obviously do not know at present) in this scenario?
Is there any special calling mechanism in this case?
Does calling mechanism change when call is synchronous and when it is asynchronous?
Can you suggest some type of binding which is readily available in this case?
1.) If the services are on the same box, use named pipes, unless you have any compelling reason not to, to communicate with each other. While WCF proper doesn't care about what you're doing as long as the address, binding and contract all match up (see what I did there?), .NET will when it comes to making network connections. The fewer you use, the better. (see http://msdn.microsoft.com/en-us/library/fb6y0fyc.aspx for more details)
2.) As stated in #1, if they're talking on the same box, use named pipes unless there's a good reason not to.
3.) Can you provide a little more detail on what you mean by this or what you're planning on doing? A lot of this is built out for you, so assuming you're familiar with implementing async methods and using async callbacks, the short answer is yes, it's different than calling an operation synchronously, but that's to be expected. Or do you mean IsOneWay = true? If that's the case, the calling mechanism is the same but there can be a number of other gotchas (e.g. faults)
4.) Named Pipes on the same box, BasicHttp otherwise (unless you need any of the additional features from WS).
but they can be on separate IIS server
In this case, you either can't use Windows authentication (if you were using it) or you have to set up some special delegates stuff on the domain to make it work. Windows Authentication won't "hop" between different servers. Here's some info on that, there's a lot of reading out there on the subject.
If they stay on the same server or you're not using Windows authentication, then it shouldn't be a problem.
Does calling mechanism change when call is synchronous and when it is
asynchronous?
Shouldn't matter, it's all the same on the service end. I will say that if the client calls X and X calls Y, X might as well call Y synchronously because it can't return to the client until Y is done anyway. (If X calls Y and Z, then X making async calls may make more sense.)
Can you suggest some type of binding which is readily available in
this case?
If you were using WSE before, then BasicHttpBinding is going to be the one closest to what you were doing and will look pretty familiar in what it outputs. It's also the simplest one to work with.
There shouldn't be anything special needed just because a WCF service method calls another WCF service. A WCF service doesn't "care" what other application types are calling its methods so long as they use the correct service contract, data contract, endpoint, and binding settings.
Just make sure that both service methods return promptly, and don't cause execution to block for long periods of time.

Direct Channel usage vs using a Proxy?

As the title implies I am trying to get an understanding of why in WCF sometimes people choose to "generate proxies" vs using a ChannelFactory to manually create new channel instances. I have seen examples of each, but haven't really found any explanations of WHY you would go for one vs the other.
To be honest I have only ever worked with channels and the ChannelFactory<T> from code I have inherited, ie:
IChannelFactory<IDuplexSessionChannel> channelFactory =
binding.BuildChannelFactory<IDuplexSessionChannel>();
_duplexSessionChannel = channelFactory.CreateChannel(endpointAddress);
So why would I "generate a proxy"? What are the benefits and drawbacks?
The main difference is this:
generating a proxy only requires you to know the URL where the service resides. By generating the proxy, everything else (the service contract and the data contracts involved) will be determined by inspecting the metadata of the service
in order to directly create a ChannelFactory<T>, you must have direct access to the assembly that contains that service contract T for which you're generating a channel factory. This only ever works if you basically control both ends of the channel and you can share the assembly that contains those service contracts. Typically, with a third-party service, this won't be the case - with your own services, yes.
The second important point is this:
creating a generated proxy basically does the two steps that you would do - create a ChannelFactory<T>, and from that, create the actual channel - in a single constructor. You have no control over these two steps.
doing your own Channel creation is beneficial, since the creation of the ChannelFactory<T> is the expensive step - so yo could cache your channel factory instance somewhere. Creating and re-creating the actual channel from the factory is much less involved step which you can do more frequently
So if you do control both ends of the communication, service and client, you do have the option to share the service contracts in a separate assembly, and thus you have more options.
With most third-party services, you just simply don't have that option.
Using a proxy is simpler and easier to understand. You get to deal in terms of simple things - classes and methods on those classes - instead of complex, network-related things like channels.
OTOH, this is not made easier by the design flaw in WCF that prevents the same simple use of a WCF proxy that we could do with ASMX proxies:
using (var client = new MyServiceClient())
{
}
If you use this pattern with WCF, you can lose the original exception when the block is exited due to an exception. client.Dispose() can throw an exception, which will overwrite the exception originally being thrown. A more complex pattern is required.
This may help you:
When to use a proxy?
If you have a service that you know is going to be used by several applications or is generic enough to be used in several places, you’ll want to use the proxy classes.
When to use ChannelFactory?
ChannelFactory class is used to construct a channel between the client and the service without the need of a proxy. In some cases, you may have a service that is tightly bound to the client application. In such a case, you can reference the Interface DLL directly and use ChannelFactory to call your methods using that.
You could also refer following link to understand the difference between Channel Factory and Proxy class
http://ashishkhandelwal.arkutil.com/wcf/channelfactory-over-proxy-class-in-wcf/
The main advantage of the channelFactory is you can create the proxy at runtime dynamically on the fly. With SvcUtil (Add web reference in VS) you create the proxy at design time, so it's implementation is more static.

WCF - Domain Objects and IExtensibleDataObject

Typical scenario. We use old-school XML Web Services internally for communicating between a server farm and several distributed and local clients. No third parties involved, only our applications used by ourselves and our customers.
We're currently pondering moving from XML WS to a WCF/object-based model and have been experimenting with various approaches. One of them involves transferring the domain objects/aggregates directly over the wire, possibly invoking DataContract attributes on them.
By using IExtensibleDataObject and a DataContract using the Order property on the DataMembers, we should be able to cope with simple property versioning issues (remember, we control all clients and can easily force-update them).
I keep hearing that we should use dedicated, transfer-only Data Transfer Objects (DTOs) over the wire.
Why? Is there still a reason to do so? We use the same domain model on the server side and client side, of course, prefilling collections, etc. only when deemed right and "necessary." Collection properties utilize the service locator principle and IoC to invoke either an NHibernate-based "service" to fetch data directly (on the server side), and a WCF "service" client on the client side to talk to the WCF server farm.
So - why do we need to use DTOs?
Having worked with both approaches (shared domain objects and DTOs) I'd say the big problem with shared domain objects is when you don't control all clients, but from my past experiences I'd usually use DTOs unless it development speed were of the essence.
If there's any chance that you won't always be in control of the clients then I'd definately recommend DTOs, because as soon as you share your domain objects with someone else's client application you start tying your internals to someone else's dev cycle.
I've also found DTOs useful when working in a versioned service environment, which allowed us to radically change the internals of our app but still accept calls to the old versions of our service interfaces.
Finally, if you have a lot of client applications it might also be beneficial to use DTOs as you're then protected with an easily versionable service.
In my experience DTOs are most useful for:
Strictly defining what will be sent over the wire and having a type specifically devoted to that definition.
Isolating the rest of your application, client and server, from future changes.
Interoperability with non-.Net systems. DTOs certainly aren't a requirement, but they make it easier to design "safe" types.
In your scenario these design features may not matter that much. I've used WCF with both strict DTOs and shared Domain Objects and in both scenarios it worked great. The only thing I noticed when sending Domain Objects over the wire was that I tended to send more data (and in unexpected ways) then I needed to. This was likely more due to my lack of experience with WCF than anything else; but it's something you should definitely be wary of should you choose to go that route.