WCF: Building a Basic WCF Service

WCF is good. Perhaps great. It fixes a bunch of problems we never knew existed, and adds a bunch more brand new, exciting ones. If you use Web Services, .NET Remoting, or any other wacky scheme to have a program communicate with another program (or application tier or server or process or whatever), WCF is for you.

It’s very powerful. It’s very flexible. Unfortunately, this also means it’s very difficult to find simple answers on how it works. I’m going to show you, as quickly and simply as possible, how to get up and running with WCF under a common and useful scenario. Understand, though, that I’m showing you one thing you can do with WCF; I’m not showing you how all of WCF works.

WCF is based around the idea of Services. A Service is essentially a class that you can access from outside of the application where the class lives, even across the Internet. Let’s have a look at a simple WCF service:

Imports System.ServiceModel

<ServiceContract()> _
Public Class Test

    <OperationContract()> _
    Public Function GetLocalTime(ByVal includeDate As Boolean) As String

        If includeDate Then
            Return Now.ToString
        Else
            Return Now.TimeOfDay.ToString
        End If

    End Function

End Class
As you can see, it’s really just an ordinary class. <ServiceContract()> marks the class as a WCF service, and <OperationContract()> marks the function as an operation of the service, so that you can access it outside of its application. In many samples, you’ll see this class split between an interface (the contract) and a class (the service). This is probably a good idea, but it’s not required.

If that code won’t compile, you probably need to add a reference to System.ServiceModel.

Believe it or not, that’s it. You’ve made a service. Easy!

No comments:

Post a Comment


Copyright © 2010 Paul Guenette and Matthew Sleno.