Programming WCF Services

Juval Lowy

Mentioned 25

Provides information on developing service-oriented applications for Windows.

More on Amazon.com

Mentioned in questions and answers.

For those just starting to learn WCF, what are the major/basic things I should look at and learn first?

What concepts would you recommend to learn first, to be productive in WCF?

What resources/articles/training/books would you recommend to someone learning WCF?

In C#, for example, one can learn LINQ at a later stage. Along similar lines, in WCF also there should be basics to learn first, and then later invest time in advanced features to enhance productivity.

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

alt text

Besides that book, I also really learned a lot from these two one-hour screencasts on WCF:

Don't miss this GREAT Book:

alt text
Ron Jacobs, (Senior Technical Evangelist for WCF at Microsoft) wrote on its forewords that "The best testament to this is to wander the halls of building 42 in Redmond (where the WCF team works); in many of the offices you will see Programming WCF Services on the shelf."
So from that I gathered that the team at Microsoft first wrote WCF and then they bought this book to understand what they actually have written!!

But seriously, I strongly recommend this book not to only understand WCF but also to learn how Juval Löwy - one of the most prominent distributed systems experts in the world today - thinks and looks at WCF and the concept of designing Enterprise SOA applications in general.

Other posts are outdated. Please don't close my post or vote it down.

Could anyone recommend a good quality WCF book for beginner/intermediate/expert?

Belows are the books I read, but I feel that the first book is good for the first few chapters.

The second book is really good. But it does NOT have separated code example for most of the example mentioned in the book. Thus, it is difficult to test them individually. It only shows the main code on the book, and combine all code in one solution.

Essential Windows Communication Foundation (WCF): For .NET Framework 3.5

Programming WCF Services: Mastering WCF and the Azure AppFabric Service Bus Juval Lowy

Edit

Is there anyone who created the code example from the second book (Juval Lowy), and would like to share it.

Or

I need to wait for the second version for this book: Learning WCF: A Hands-on Guide

I don't think she has updated it for WCF 4, but Michele Bustamante's Learning WCF is a great beginner's book. She has step by step exercises and explanations and writing style is a tad easier to read imo.

As we want to develop a new product using Asp.Net MVC 3. The key point here is everything we talk to database by WCF web service.

We are in the phase where we need to decide whether we host WCF web service in IIS OR self hosting with Windows Service.

I raised this question just because I want to know that, what would be the better option to host WCF service that would satisfy my below conditions.

  • We're expecting 120 concurrent request / second. (May be 12,000 request/visit per day)
  • Security aspect (Specially WCF Service security)
  • Maintainability
  • Handling user's concurrent request at the same time (Can Windows Service handle multiple concurrent request comparing to IIS?)

Please do let me know whether I go for IIS hosting OR self hosting with Windows service.

Thanks in advance.

(Could anybody please suggest on this as this is a very crucial part to have decision for further process.)

You might interest, This is the "general decision tree" from "Programming WCF Services", Juval Lowy.

Choosing a host for an Internet service: For an internet application (that is, an application that receives calls from clients across the Internet)

Choosing a host for an Internet service

Choosing a host for Intranet service: For an intranet application (that is, an application that receives calls from clients within the same intranet), Choosing a host for an Intranet service

I am taking over a project to replace an ancient legacy system from the ground up. Before I came on, the company hired a consultant who put together a basic sketch of the system and pushed SOA heavily. This resulted in a long list of "entity services", with the intention of them being composed into more complex service combinations. For instance, a user wanting committee info would hit the "Committee" service, which then calls the "Person" service to get its members, and the "Meeting" service to get its meetings, and so on.

I understand the flexibility gains in this, but my concerns are about performance. It seems to me that a system built with such a fine level of granularity to its services spends too many resources on translating service messages, and the performance will be unacceptable. It also seems to me that the flexibility gains can still be made using basic reusable objects, although in that case the benefit of a technology-agnostic interface is lost to gain performance.

For more background: The organization requesting this software does not currently have a stable of third-party software suites that need integrating with. This software will replace all suites. There are also currently no outside consumers who need to access the data outside of the provided website interface -- all service calls will be from other pieces inside our system. The choice of SOA in this case seems entirely based on the concept of "preparation".

So my question -- what level of granularity is acceptable in a stable of services without sacrificing performance? Am I being too skeptical of the performance hits we'll take implementing all our entities as services? Should functionality be available as web services only when they are needed, with the "preparation" focus instead going into designing the business layer for the probability of services later being dropped on top of it?

First off, finding the "sweet spot" in the number of services is difficult for sure. Too many services, and your integration costs suffer, too few, and your implementation costs suffer. You have to find a good balance.

My advice to you is to follow Juval Lowy's methodology in that you should break down your services by areas of volatility, or areas of change. This will give you your granularity level. You should also read his WCF book if you can.

As for the performance, WCF will inherently support many thousands of calls per second depending on your use cases and hardware. Services calling services is not a problem. The platform will support it if you do your part. For example, use the right binding for the right scenario (named pipes to call services on the same machine and TCP to call services across machine where possible). You should also implement a vertical slice of the application and do performance testing before building the rest of the application. This will verify your architecture.

Every example of the Repository Pattern I have seen deals with a very simple use case - one object type and the most basic CRUD operations. The Repository is then very often plugged straight into an MVC controller.

Real-world data access just isn't like this. Real-world data access scenarios can involve complex graphs of objects and some form of transactional wrapper. For example, suppose I want to save a new Order. This involves writing to the Order, OrderDetails, Invoice, User, History and ItemStock tables. All of this must be transacted, committed or rolled back. Normally I'd pass around something like an IDbTransaction and an IDbConnection and bundles the whole operation in a service layer.

Where does the Repository Pattern fit with this? Am I missing something (Unit Of Work perhaps)? Are there any more realistic examples of Repositories in use than the usual canned blog snippets?

Appreciate any light.

I like to think of a repository as another layer of abstraction. You should only add layers of abstraction when the cost of their implementation is less than the cost of NOT doing the implementation (code maintenance, support, enhancements, etc).

Remember that the purpose of the repository pattern is to separate the logic that retrieves the data (CRUD) and maps it to the entity model from the business logic that acts on the model. What this often ends up doing/looking like in the real world is some form of business entities, that abstract the underlying physical data model.

As far as your transaction question, yes, this relates more to the Unit of Work pattern. Since you mentioned services, I would encourage you to NOT pass around your connection to your various data access classes/methods, but to instead allow WCF to manage the transaction for you using auto enlistment. Here is an extract of Juval Lowy's WCF book (highly recommended) that explains the how and why of this method of transaction management.

So to answer your question, the repository pattern fits in as a way to abstract the physical data model and to separate the CRUD/mapping from the business logic.

I've written a C# windows service which can write messages to a custom EventLog or to any number of files. These messages are all marked with some priority (so, for example, only ERRORs and WARNINGs get stored in the EventLog, but if desired a lot more can be stored to a file).

What I'd like to do now is create a GUI that can listen for these messages and display them in real-time. Allowing a user to watch the current messages (at whatever their desired priority level), without the need to store everything to a file. I assume this is a separate program with some form of hook into the service, but I'm unsure of where to start.

This is my first real windows service, so I seem to be missing some keywords for finding out how to do this... Are there any code samples, tutorials, references, etc. for how to do something like this?

UPDATE
A lot of helpful answers, I love it when there's many ways to solve a problem! I think I'm going to implement a self-hosting WCF based solution. I'm still very light on the details as I'm trying to learn about WCF (I believe it will prove quite useful for me in other projects)... but thus far, I've found the videos here to be the most helpful as an intro how-to.

I know this has already been mentioned, but use Windows Communication Foundation (WCF). Specifically, use the Publish-Subscribe Framework developed by Juval Lowy, author of Programming WCF Services. The details are described in this excellent MSDN article, and the source code is available for free at Lowy's website.

The neat thing about this framework is that it decouples the publisher, e.g., your Windows service, from any subscribers, e.g., your GUI. The publisher "publishes" events that are of interest to the Pub/Sub Service, which is always available. From the publisher's point of view, it doesn't matter if there are any subscribers or not. The Pub/Sub Service takes care of routing events to any and all registered subscribers. In this way, your Windows service publishes events as they occur, your GUI will subscribe/unsubscribe to the Pub/Sub Service when it loads/exits, and the Pub/Sub Service will notify your GUI as events occur.

I have used this setup in my project, and it works extremely well.

I am newbie to WCF, and I'd like to know how WCF provides more security over ASMX web services?

And which binding we prefer when we consider security part?

How do I choose the best binding as there are that many ?

Many thanks..

That's a very very broad question.

WCF provides a lot more security by providing a lot more capabilities and options out of the box: it supports not only transport security (using SSL and https to secure your link, like ASMX) but also supports message encryption, and messages are by default encrypted and digitally signed.

This topic Bindings and Security on MSDN might be a good starting point - it explains the various security-related features of each binding. The topic Programming WCF Security goes into more details, and the ultimate "one-stop site" for WCF security is the WCF Security Guidance site on Codeplex created and maintained by the Patterns & Practices group at Microsoft.


As for choosing the right binding - I would recommend the decision flowchart that Juval Lowy presents in his excellent book Programming WCF Services (for intermediate to advanced developers).

I have a specific case and I want to know the best practice way to handle it.

I make a specific .NET framework (web application). This web application acts like a platform or framework to many other web applications through the following methodology :

We create our dependent web applications (classes for the project business, rdlc reports) in a separate solutions then build them.

After that we add references to the resulted dll in the framework.

And create set of user controls (one for each dependent web application) and put them in a folder in the framework it self.

It works fine but any modification to a specific user control or any modification to any one of the dependent web applications. We have to add the references again and publish the whole framework !!

What I want to do is make those different web applications and the framework loosely coupled. So I could publish the framework one and only one and any modifications to the user controls or the different web applications just publish the updated part rather than the whole framework .

How to refactor my code so I can do this?

The most important thing is :

Never publish the whole framework if the change in any dependent application, just publish the updated part belongs to this application .

If loose coupling is what you are after, develop your "framework(web application)" to function as a WCF web service. Your client applications will pass requests to your web services and receive standard responses in the form of predefined objects.

If you take this route, I recommend that you implement an additional step: Do not use the objects passed to your client applications directly in your client code. Instead, create versions of these web service objects local to each client application and upon receiving your web service response objects, map them to their local counterparts. I tend to implement this with a facade project in my client solution. The facade handles all calls to my various web services, and does the mapping between client and service objects automatically with each call. It is very convenient.

The reason for this is that the day that you decide to modify the objects that your web service serves, you only have to change the mapping algorithms in your client applications... the internal code of each client solution remains unchanged. Do not underestimate how much work this can save you!

Developing WCF web services is quite a large subject. If you are interested, a book that I recommend is Programming WCF Services. It offers a pretty good introduction to WCF development for those who come from a .NET background.

I have a windows service that is hosting a WCF service on a server. I am using InstanceContextMode.PerSession attribute. The services function well per my requirements.

I would now like to implement a visual feedback for the WCF service, like a logger, preferably in a list box in a windows form. I would like all calls from all clients and the subsequent actions to be recorded in this form. I read that having a UI for a service is not a good idea. Can someone point me in a direction to achieve this in a thread safe way.

What you're talking about essentially is having your WCF service within your Windows service provide event notifications to a UI front-end when something "interesting" happens. Fortunately, there is a Publish-Subscribe Framework developed by Juval Lowy, author of Programming WCF Services. The details are described in this excellent MSDN article, and the source code is available for free at Lowy's website.

The neat thing about this framework is that it decouples the publisher, e.g., your WCF service in your Windows service, from any subscribers, e.g., your GUI. The publisher "publishes" events that are of interest to the Pub/Sub Service, which is always available. From the publisher's point of view, it doesn't matter if there are any subscribers or not. The Pub/Sub Service takes care of routing events to any and all registered subscribers. In this way, your WCF service in your Windows service publishes events as they occur, your GUI will subscribe/unsubscribe to the Pub/Sub Service when it loads/exits, and the Pub/Sub Service will notify your GUI as events occur.

I have used this setup in my project, and it works extremely well.

EDIT: I understand the desire to have your own UI that displays events from your Windows service-hosted WCF service. Another option would be to leverage an application log that is accessible from the Windows native Event Viewer (eventvwr.msc). If this approach is acceptable, take a look at my instructions here for how to set that up from your Windows service.

I have recently come across the term Instance Deactivation.

a) What is that?

b) What for we need that?

c) In what context will it be useful?

I am looking for a simple answer that can be easily undestandable and if posible with some pseudo code.

Thanks

When a WCF method is invoked, it is passed to a service instance.

Instance Deactivation simply refers to the moment where the WCF system disposes of this instance.

In a Per-Call Service, instance deactivation will occur after each method call.

In a Per-Session Service, instance deactivation will occur when the client calls Close on the proxy, or when the transport-session's inactivity timeout is reached.

In a Singleton Service, instance deactivation will occur when the Service Host is closed.

You can also configure individual service methods to trigger instance deactivation:.

[OperationBehavior(ReleaseInstanceMode = ReleaseInstanceMode.AfterCall)]
 public void MyMethodWhichTriggersAnAutomaticRelease()
 {
     // ...
 }

As well as this, you can manually trigger a service instance release:

public void MyMethodWhichTriggersAManualRelease()
{
     OperationContext.Current.InstanceContext.ReleaseServiceInstance();
}

Juval Lowy has this to say on whether you should manually override the standard instance deactivation mechanisms:

Instance deactivation is an optimization technique, and like all optimization techniques, you should avoid it in the general case. Consider using instance deactivation only after failing to meet both your performance and scalability goals and when careful examination and profiling has proven beyond a doubt that using instance deactivation will improve the situation.

At work, our service calls follow the pattern of:

  1. Create a proxy that allows you to hit a service on our business tier
  2. upon hitting the service, it creates a new response instance
  3. instantiates a new instance of one of our business code classes
  4. Assigns the result of calling whatever function on the new instance to the response
  5. Returns the response back through the proxy

So it always looks like this:

Dim someRequest as Request = CreateSomeSortOfRequest()
Dim results as Response = Nothing
using proxy as IResultProxy = OurLibrary.Proxy(Of IResultProxy).Create()
    results = proxy.GetResults(request)
End Using 

Then:

Dim results as Response = Nothing
Using whateverBusiness as new BusinessClass
    results = whateverBusiness.ComputeWhatever(request)
End Using
Return results

Pretty basic stuff, right? Well the guys who have worked there for a little over 20 years now will go on and on about how none of these business classes should ever have any member variables of any kind. Ever. Wanna perform some really complicated operation? Better be prepared to pass 10 to (and I've seen it) 30 parameters.

All of this, to me, seems like bad practice. As long as you remain in that narrow scope, hand off a request to a new instance of a business class, ask it to perform whatever, it performs whatever logic necessary within itself, return the result, and carry on with your day.

I've investigated and we only ever use threading ourselves in one location in the system, and that just fires off different service calls (all of which follow the above pattern). We don't use instance pools, static variables, or anything else like that, especially since we have the above stated issue that we have a running belief that there should never be any class scoped variables.

Am I crazy for thinking that having these classes with extremely tight and locked down entry points (i.e. no outside access to internal variables) is perfectly fine, especially since there is no way to access the instances of the business class outside the scope of the service call? Or are my elders correct for stating that any private member variable in a class is non-threadsafe and should never be used?

I guess I should mention that the business classes pretty much always load some data from the database, try to piece that data together into, often, very deep hierarchal structures, then return (or the opposite; taking the object, breaking it apart, and performing, sometimes, hundreds of database calls to save).

Wanna perform some really complicated operation? Better be prepared to pass 10 to (and I've seen it) 30 parameters

Sounds like they don't want any state (public anyway) on their business classes, an understandably noble vision as it is but rarely does it prove to be useful or practical as a general rule. Instead of 30 parameters, maybe they should pass in a struct or request class.

You could point out to them that in their effort to prevent state, that 10-30 parameters comes with its own set of problems.

As stated in the documentation for the brilliant code analysis tool nDepend:

nDepend:

NbParameters: The number of parameters of a method. Ref and Out are also counted. The this reference passed to instance methods in IL is not counted as a parameter.

Recommendations: Methods where NbParameters is higher than 5 might be painful to call and might degrade performance. You should prefer using additional properties/fields to the declaring type to handle numerous states. Another alternative is to provide a class or structure dedicated to handle arguments passing (for example see the class System.Diagnostics.ProcessStartInfo and the method System.Diagnostics.Process.Start(ProcessStartInfo)) - Holy swiss cheese Batman, tell me more.

It's arguably no different to when the client passes a request object to the WCF service. You are passing request objects aren't you?

OP:

Am I crazy for thinking that having these classes with extremely tight and locked down entry points (i.e. no outside access to internal variables) is perfectly fine

OK it sounds like the system has been around for a while and has had some best practices applied by your elders during its construction. That's good. However such a system is arguably only going to continue being robust as someone follows what-ever rules that were setup...and from what you say sound quite bizarre and somewhat ill-informed.

It might also be an example of accidental architecture where the system is just because it is.

e.g. if someone goes and adds a public method and say some public properties or makes what was a private field public is likely to upset the applecart.

I once had the misfortune of working on a legacy system and though it appeared to run without incident, it was all rather fragile due to the exorbitant amount of public fields. (mind you this was c++!)

Someone could have said:

"well don't touch the public fields"

to which I could reply:

"well maybe we shouldn't make the fields public"

Hence their desire to have no instance fields. The notion that c# classes with "member variables of any kind" is naughty is not the real source of concern. Instead I suspect the problem is that of thread safety and for that they should be looking into how the caller or callers be made thread-safe not the business class in this case.

Enforcing thread safety by not having state, though effective is kind of a sledgehammer approach and tends to annoy other parts of OO sub-systems.

enter image description here

WCF Threading Models

It sounds to me they are performing applying old-school threading protection in WCF where WCF has it's own way of guaranteeing thread-safety in a way quite similar to how the Apartment model was successful for COM.

Instead of worrying about lock()s; and synchronisation, why not let WCF serialise calls for you:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, 
    ConcurrencyMode = ConcurrencyMode.Single)]
public partial class MyService: IMyService, IDisposable
{
    // ...
}

InstanceContextMode.PerSession essentially tells WCF to create a unique private instance of the service per client proxy. Got two clients calling? Well that means two instances of MyService will be created. So irrespective of what instance members this class has its guaranteed not to trod on the other instance. (note I don't refer to statatics here)

ConcurrencyMode = ConcurrencyMode.Single tells WCF that calls to this service instance must be serialised one after the other and that concurrent calls to the service are not allowed. This ties in with the InstanceContextMode setting.

Just by setting these two but very powerful settings in WCF you have told it to not only create private instances of your WCF service such that multiple clients can't trod on it, but that even if the client shared it's client proxy in a thread and attempted to call one particular service instance concurrently, WCF guarentees that calls to the service will be serialised safely.

What does this mean?

  • Feel free to add instance fields or properties to your service class
  • such members won't be trodden on by other threads
  • when using WCF, there is generally no need for explicit thread locking in your service class (depending on your app, this could apply to subsequent calls. see below)

It does not mean that per-session-single services only ever allow one client at a time. It means only one call per client proxy at a time. Your service will most likely have multiple instances running at a particular moment having a jolly good time in the knowledge that one can't throw stones at the other.

Roll-on effects

As long as you remain in that narrow scope, hand off a request to a new instance of a business class

Since WCF has established a nice thread-safe ecosystem for you, it has a nice follow-on effect elsewhere in the call-stack.

With the knowledge that your service entry point is serialised, you are free to instantiate the business class and set public members if you really wanted to. It's not as if another thread can access it anyway.

Or are my elders correct for stating that any private member variable in a class is non-threadsafe

That depends entirely on how the class is used elsewhere. Just as a well designed business processing layer should not care whether the call stack came from WCF; a unit test; or a console app; there may be an argument for threading neutrality in the layer.

e.g. let's say the business class has some instance property. No drama, the business class isn't spawning threads. All the business class does is fetch some DB data; has a fiddle and returns it to the caller.

The caller is your WCF service. It was the WCF service that created an instance of the business class. But what's that I hear you say - "the WCF service instance is already thread-safe!" Exactly right and thank-you for paying attention. WCF already set up a nice thread safe environment as mentioned and so any instance member in the business class shouldn't get obliterated by another thread.

Our particular WCF thread is the only thread that is even aware of this particular business class's instance.

Conclusion

Many classes in .NET have state and many of those are in private fields. That doesn't mean it's bad design. It's how you use the class that requires thought.

A WinForms Font or Bitmap object has both state; I suspect even with private members; and shouldn't arguably be fiddled with concurrently by multiple threads. That's not a demonstration of poor design by Microsoft's part rather something that should have state.

That's two classes created by people much smarter than you, me and your elders I suspect, in a codebase larger than anything we will ever work on.

I think it is fantastic that you are questioning your elders. Sometimes we don't always get it right.

Keep it up!

See Also

  • Lowy, Juval, "Programming WCF Services: Mastering WCF and the Azure AppFabric Service Bus", Amazon. The WCF bible - a must read for prior to any serious dabbling into WCF goodness

enter image description here

enter image description here

  • nDepend, a truly marvelous and powerful code analysis tool. Though one may be forgiven into thinking it's a FxCop-type-tool and though it does support such a feature, it does that and more. It analyses your entire Visual Studio solution (and stand-alone libraries if you wish) investigating coupling for one and excessive use of parameters as another. Be prepared for it pointing out some embarrassing mistakes made by the best of us.

Comes with some groovy charts too that look impressive on any dashboard screen.

Can any one suggest me a good book for .Net Web Services beginers (C#)

Try this book, very highly recommended and current

ASP.NET 4 in C# and VB.NET

If you're looking for WCF, this one is great:

Essential WCF

If you're only just starting to do web services, I would strongly recommend you go and check out WCF. It's the current and future standard for communications between machines - web services and a lot more.

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF

The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming. He just recently completed a third edition, which covers WCF in .NET 4 and AppFabric and the Azure Service Bus, too.

Programming WCF Services including AppFabric and Azure ServiceBus

I am preparing for the 70-513 certification exam. Does anyone know a new good book for this ?

I have a parent program (Server) and a child program (client), and the two can have a full-duplex communication with each other using named pipes: here

My actual client and server are a bit more complicated, my client needs some input parameters(objects) in order to do its work, so I was thinking to send these using the pipe that I have created. some people talk about WCF. this is the first time I here WCF, How can I send my objects through named pipe?

Thanks

Actually using WCF is the best way to send objects between two processes. Even you can still using pipes and named pipes for it. I recommend you this book for further knowledge.

Anyway if you want to use pipes between two processes to send and receive objects you must serialize them. This is, convert the objects to be sent in arrays of bytes, xml, or soap format. There are tons of examples in the web showing how to send data through sockets and pipes. Both are very similar.

I suggest you to create an independent assembly with classes that will be sent and received. That assembly must be referenced by both processes.

I hope this helps you.

I have developed a WCF service for consumption within the organization's Ethernet.
The service is currently hosted on a windows-service and is using net.tcp binding.
There are 2 operation contracts defined in the service.
The client connecting to this service is a long running windows desktop application.
Employees(>30,000) usually have this client running throughout the week from Monday morning to Friday evening straight.

During this lifetime there might be a number of calls to the wcf service in question depending on a certain user action on the main desktop client. Let us just say 1 in every 3 actions on the main desktop application would trigger a call to our service.

Now we are planning to deploy this window service on each employee's desktop
I am also using `autofac` as the dependency resolver container.
My WCF service instance context is `PerSession`, but ideally speaking we have both the client and service running in the same desktop (for now) so I am planning to inject the same service instance for each new session using `autofac` container.
Now am not changing the `InstanceContext` attribute on the service implementation because in future I might deploy the same service in a different hosting environment where I would like to have a new service object instance for each session.

Like mentioned earlier the client is a long running desktop application and I have read that it is a good practise to `Open` and `Close` the proxy for each call but if I leave the service to be PerSession it will create a new service instance for each call, which might not be required given the service and client have a 1-1 mapping.
Another argument is that I am planning to inject the same instance for each session in this environment, so Open & Close for each service call shouldn't matter ?
So which approach should I take, make the service `Singleton` and Open Close for each call or Open the client-side proxy when the desktop application loads/first service call and then Close it only when the desktop application is closed ?

My WCF service instance context is PerSession, but ideally speaking we have both the client and service running in the same desktop (for now) so I am planning to inject the same service instance for each new session using autofac container

Generally you want to avoid sharing a WCF client proxy because if it faults it becomes difficult to push (or in your case reinject) a new WCF to those parts of the code sharing the proxy. It is better to create a proxy per actor.

Now am not changing the InstanceContext attribute on the service implementation because in future I might deploy the same service in a different hosting environment where I would like to have a new service object instance for each session

I think there may be some confusion here. The InstanceContext.PerSession means that a server instance is created per WCF client proxy. That means one service instance each time you new MyClientProxy() even if you share it with 10 other objects being injected with the proxy singleton. This is irrespective of how you host it.

Like mentioned earlier the client is a long running desktop application and I have read that it is a good practise to Open and Close the proxy for each call

Incorrect. For a PerSession service that is very expensive. There is measurable cost in establishing the link to the service not to mention the overhead of creating the factories. PerSession services are per-session for a reason, it implies that the service is to maintain state between calls. For example in my PerSession services, I like to establish an expensive DB connection in the constructor that can then be utilised very quickly in later service calls. Opening/closing in this example essentially means that a new service instance is created together with a new DB connection. Slow!

Plus sharing a client proxy that is injected elsewhere sort of defeats the purpose of an injected proxy anyway. Not to mention closing it in one thread will cause a potential fault in another thread. Again note that I dislike the idea of shared proxies.

Another argument is that I am planning to inject the same instance for each session in this environment, so Open & Close for each service call shouldn't matter ?

Yes, like I said if you are going to inject then you should not call open/close. Then again you should not share in a multi-threaded environment.

So which approach should I take

Follow these guidelines

  1. Singleton? PerCall? PerSession? That entirely depends on the nature of your service. Does it share state between method calls? Make it PerSession otherwise you could use PerCall. Don't want to create a new service instance more than once and you want to optionally share globals/singletons between method calls? Make it a Singleton

  2. Rather than inject a shared concrete instance of the WCF client proxy, instead inject a mechanism (a factory) that when called allows each recipient to create their own WCF client proxy when required.

  3. Do not call open/close after each call, that will hurt performance regardless of service instance mode. Even if your service is essentially compute only, repeated open/close for each method call on a Singleton service is still slow due to the start-up costs of the client proxy

  4. Dispose the client proxy ASAP when no longer required. PerSession service instances remain on the server eating up valuable resources throughout the lifetime of the client proxy or until timeout (whichever occurs sooner).

  5. If your service is localmachine, then you consider the NetNamedPipeBinding for it runs in Kernel mode; does not use the Network Redirector and is faster than TCP. Later when you deploy a remote service, add the TCP binding

I recommend this awesome WCF tome

enter image description here

I have not worked on Web Services, but now I am planning to work on WCF Services in my next web application project. Do we need to have prior working experience on Web Services to work on WCF ?

can we start learning/working on WCF directly with out working experience in Web Services ?

You do not need any prior experience in web services to use WCF, though it would of course help in some situations. Having said that, WCF does have a learning curve (like everything), so you should consider going through some training, like the excellent Pluralsight training.

In addition to some sort of training, a must have resource for WCF in my opinion is Juval Lowy's book, Programming WCF Services.

Good luck!

I have two dumb/rookie questions. My problem is, I have NO idea where to begin learning this stuff.

Traditionally, I am an ASP.NET developer. I am familiar with creating and consuming traditional web services (.asmx) in ASP.NET. Now, I want to create some REST based services that adhere to the HTTP verbs approach. I intend to use WCF services to accomplish this. In addition, I want to create my services like Twitter in a fashion where the caller can reference [serviceName].[xml|json]. Unfortunately, i do not know how to allow the caller to specific the format. It seems like I need to create two seperate services which seems odd. Am I way off? Can someone point me in the right direction?

Thank you!

Juval Lowy's 2nd edition on Programming WCF is available. This should be an excellent source; his first book was outstanding. Michele Leroux Bustamante is another excellent author on WCF, but her 2nd edition book isn't due for another few months, so go with Juval Lowy.

Essentially, WCF separates protocol (binding) from code, so you should be able to write the service once, and use multiple end points (address, binding, etc.) to provide different formats.

I want to learn step by step how to create a WCF service, starting from something very simple.

Can anyone help me?

See this series of web casts by Michelle Bustamonte.

If you are a beginner, this is one of the best sources to learn WCF.

You can also start with the book Learning WCF.

Also take a look at these SO posts -

learning the basics of WCF

What is the best way to learn WCF?

Good and easy books/tutorials to learn WCF latest stuff

I found this webcast to be an excellent introduction to WCF.

I would also recommend anything by Juval Lowy, especially his book Programming WCF Services. His website, IDesign.net, has a lot of free code downloads that I find especially instructive.

Scenario

  • So I've taken an example of a distributed application in WCF that implements the Observer pattern.
  • Ihave put the server-side into a windows service and added some classes to do some calculations, which I intend to pass the results back to the client.

The solution is made up of 3 projects.

  • Server-Side Windows Service - Processes all the data/Performs calculations.
  • Common Objects Class Library.
  • Client-Side Windows Forms Application.

They connect and exchange data using a WCF Service that implements the Observer pattern to allow for two-way data exchange.

On The Server-Side:

I've got 3 classes:

  1. Class one calculates X.
  2. Class two calculates Y.
  3. Class three calculates Z.

The data from these 3 calculations is then published via the WCF Service to the Client-Side.

On The Client-Side:

Here's the TRICKY part………..

I want each set of data from each of these 3 classes to be displayed on a GridControl on a DIFFERENT Form.

So it will be as follows:

  1. Class X data will be published to the MainForm.
  2. Class Y data will be published to the YForm.
  3. Class Z data will be published to the Zform.

The Client application, when first run, will show only the MainForm, but it will contain a menu bar to open the Yform and Zform.

Thoughts:

  • What do you think the best way to do this is?
  • Do I publish all the data to one central class and then invoke the dictionaries bound to the grid controls on each different form to update the data?
  • Or is there another way?

Appreciate the help.

Option 2 in your list would work, publish to a central class on the client and have the other forms query this class for the info. I would suggest a Publish/Subscribe pattern rather than the observer (I presume you will implement this with Duplex bindings), as it is a less coupled implementation which scales better.

This way the service will just publish info to subscribing clients.

You can implement this by hosting WCF response services on the client form, this way when one of your calculation services publishes a result, the service hosted on the WinForm can subscribe and receive this event.

If you have a requirement to keep the forms open and update them in real time you can have each form that needs data to host a service on the form, and just subscribe to different events. You can then synchronize (synchronization context) onto the UI thread and update the grid in real time i.e stock price updates.

I recommend Juval Lowy's book Programming WCF Services to help explain the concepts and provide a reference implementation of Publish/Subscribe, hosting services on forms and synchronization context.

I am uploading images as byte arrays as qucikly as possible.

I have used basicHttpBinding with MTOM encoding.

An image could be 19K or 80K in size.

I have also used net.tcp binding.

I am only interested in one-way communication - namely from client to server.

I have read that net.tcp is quicker but can have issues with firewalls?

Should I stick to basicHTTPBinding with MTOM enabled?

Thanks

The question is better answered if the application is for Internet or intranet clients.

If it is for the intranet and both client and server are using WCF; and require connected communication, stick to TCP. TCP is binary and therefore faster. [1]

If it is for the Internet and you need non-WCF clients, stick to HTTP variants. It may not be as fast as binary protocols like TCP, but what you lose in performance you gain in wider client base and firewalls are less of an issue. [1]

EDIT: In response to your comment below about WCF Internet clients I would recommend basicHttpBinding mainly because of firewalls. If your messages are large then enable MTOM as you mentioned. Again refer to Lowy in the book below.

[1] - Lowy, "Programming WCF Services", O'Reilly Media

I want to create three WCF services in an intranet. The three WCF services are independent of eachother, in sense of their functionality e.g.

  1. Validator Service - Deals with everything that has to do with validating of accounts and account holders. i.e. if an account exists, if card holder exists etc

  2. Account Service - Deals with depositing of balance in an account and depositing of balance

  3. Limit Service - Deals with checking if the amount user wants to take out is is within an account's limit.

Use case: User wants to deposit some money.

UI starts by calling account service. Account service calls validator service to check if account exists. Validator service returns boolean to indicate if an account exists. If validator service returns true then Account service then deposits money.

User wants to take out money.

UI starts by calling account service. Account service calls validator service if account exists. Validator service returns true. Account service then calls limit service to check if user can take this balance out. If the limit service returns true then accounts service calls appropriate method which reduces balance and gives balance to user.

I am planning to host them as windows services because the UI and all of these services will be deployed on the same machine.

  1. What are your thoughts regarding that?

  2. Is there any book you recommend that you recommend on such SOA architecture where services communicate with eachother? I am really concerned about its scalability, security and performance.

Thanks.

Why three separate services for operations that are linked like in that way? It seems you are taking SOA to an extreme that you don't need to.

I would create one service that dealt with account actions (deposits, withdrawals, balance inquiries, transfers, etc). Things like validating and limits, unless available to the user, I would put behind the scenes, either as private methods in the contract, or more likely in an underlying DLL that the service would reference.

Having a service that does only one thing is not, in and of itself, bad - but having multiple services do only one thing, and all of these things together fall under a single logical grouping, is overkill (IMO). I would suggest taking a good look at the business process your trying to model - the groupings (if any) should be readily apparent.

I would recommend Juval Lowry's book Programming WCF Services: Mastering WCF and the Azure AppFabric Service Bus - it's considered the WCF bible by many, and he has a whole appendix that's a good primer on SOA.

I was recently working on .net; now I want to learn WCF. Are there any topics required before going to WCF? Because somewhere I saw that WWF is necessary, is it? I want to go through the WCF tutorial.. please suggest me a right path

Thank you

The book I always recommend to get up and running in WCF quickly is Learning WCF by Michele Leroux Bustamante. She covers all the necessary topics, and in a very understandable and approachable way. This will teach you everything - basics, intermediate topics, security, transaction control and so forth - that you need to know to write high quality, useful WCF services.

Learning WCF

The more advanced topics and more in-depth look at WCF will be covered by Programming WCF Services by Juval Lowy. He really dives into all technical details and topics and presents "the bible" for WCF programming. He just recently completed a third edition, which covers WCF in .NET 4 and AppFabric and the Azure Service Bus, too.

Programming WCF Services

As for other resoures: there's the MSDN WCF Developer Center which has everything from beginner's tutorials to articles and sample code.

Also, check out the screen cast library up on MSDN for some really useful, 10-15 minute chunks of information on just about any topic related to WCF you might be interested in. Also, on CHannel9, check out the Endpoint TV Show - the older videos in this show are really good intros to WCF (create your first WCF service, create your first WCF client and so forth)

Say I have a WCF service that has access to some data that is shared between multiple clients. What is the difference between these two setups:

1) Instancing: Single, Concurrency: Multiple, with the shared data stored in instance variables.

2) Instancing: Per-Call, Concurrency: Multiple, with the shared data stored in static variables.

Is there any practical difference? Either way, I will have to make sure the shared data is thread-safe, but I'm wondering if there are any advantages for one particular approach.

Notionally, there is no difference. As you've said, either way you're gonna have to synchronize access to the shared data. Practically, the second option is better. From the definitive book on WCF, Programming WCF Services by Juval Lowy:

...per-call services are actually the preferred instance management mode for WCF services...recommend that you avoid singletons in the general case and find ways to share the state of the singleton instead of the singleton instance itself.

I use option #2 for my project. The WCF service itself is simply a thin facade to static methods of the classes where the work is performed. For example,

public class Logger
{
    private static List<Logger> _loggers = new List<Logger>();
    private static object _sync = new object();

    public static void Start()
    {
        Logger logger = new Logger();
        logger.Start();

        lock (_sync) {
            _loggers.Add( logger );
        }
    }

    private Logger()
    {
        // construct the Logger object...
    }

    private void Start()
    {
        // start the logger here...
    }
}

public class LoggingService : ILoggingService
{
    public void StartLogger()
    {
        Logger.Start();
    }
}

Obviously, I've elided many of the details, but this shows the general idea.