Home > Articles > Programming > Windows Programming

Building WCF Services with F#

  • Print
  • + Share This
  • 💬 Discuss
F# is a functional programming language from Microsoft. Scott Seely, coauthor of Effective REST Services via .NET: For .NET Framework 3.5, shows how to apply F# to Windows Communication Foundation (WCF) endpoints in .NET.

Windows Communication Foundation (WCF) has been around since .NET 3.0 and has become the dominant mechanism to expose web services on the .NET platform. During WCF's ascendance, developers have become more interested in functional programming (FP) practices. For example, Language Integrated Query (LINQ) uses many aspects of FP and is integrated into C# and Visual Basic .NET. Developers have gained great productivity boosts with LINQ, and many have chosen to dive into FP to see what else it has to offer.

These days, many .NET developers are learning F#, Microsoft's functional programming language, which is part of .NET 4.0 and Visual Studio 2010. F# is also available as a download for .NET 3.5 and Visual Studio 2008.

Mixing F# and WCF can present some challenges in terms of code you write and ways in which you deploy your services. This article explores how to write WCF contracts using F#, and then looks at how to host an F# endpoint within a website. We'll assume that you're already familiar with WCF and the Address, Binding, Contract (ABC) paradigm.

Implementing a WCF Service

A typical WCF service contract includes details about the message exchange patterns as well as names of the message parts. All applications that send messages between some sender-receiver pair send those messages using one of four primary message patterns:

  • One-way: The sender fires a message to the receiver and then disconnects. This pattern is very common in queue-based delivery and publish/subscribe systems.
  • Request/response: The sender fires off a message and receives a response. This pattern exists in REST systems (ask for a resource, get a resource) as well as Remote Procedure Call (RPC) systems (execute a method, get back a result).
  • Conversation: The sender makes a specific request to start the conversation or session. The intervening messages assume that the receiver maintains some sort of state. Eventually, a terminate message occurs, ending the session. SSL and session-oriented applications use this pattern.
  • Duplex: The sender and receiver both implement a different, well-known set of messages that either side can call.

You can implement contracts that handle all of these exchange patterns in F#. In this article, we build a contract that has a one-way message and a request/response message pair. The code also uses a class to communicate structured data.

In C#, the object and contract look like this:

[DataContract(Namespace="http://www.scottseely.com/WCFDemo")]
public class Name
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public char MiddleInitial { get; set; }
}

[ServiceContract(Namespace="http://www.scottseely.com/WCFDemo")]
public interface ISimpleService
{
    [OperationContract]
    string MyRequestReplyMessage(Name fullName);

    [OperationContract(IsOneWay=true)]
    void MyOneWayMessage(int someInt, bool someBool);
}

The MyRequestReplyMessage operation takes formatted data based on the Name DataContract and returns a string. Any message sender must wrap the content of the Name object with a parameter called fullName.

<fullName xmlns="http://www.scottseely.com/WCFDemo">
    <FirstName>Scott</FirstName>
    <LastName>Seely</LastName>
    <MiddleInitial>C</MiddleInitial>
</fullName>

Likewise, the one-way message, MyOneWayMessage, has a void return type and has an operation marked as IsOneWay=true. Based on the variable names in the C# interface, System.ServiceModel also infers that the someInt and someBool parameters appear within the SOAP body as XML:

<someInt>18</someInt>
<someBool>true</someBool>

Representing the same information in F# can be a challenge. We need to create a compatible DataContract for the Name type and an ISimpleService contract. First, we create the Name object. When creating the properties for Name, we need to think about how WCF stores and retrieves instance properties. WCF routes transformations of XML to objects through System.Runtimer.Serialization.DataContractSerializer. DataContractSerializer and other types related to its base type, System.Runtime.Serialization.XmlObjectSerializer, set the member variables and fields after object construction. This behavior requires a type that supports post-construction member changes. By contrast, functional languages typically assign values at construction and leave the values immutable for the remaining life of the object. These two behaviors are at odds with each other. To support WCF, any F# object must mark the backing storage for all exposed properties as mutable:

[<DataContract(Namespace="http://www.scottseely.com/WCFDemo")>]
type Name() =
    let mutable _firstName : string = String.Empty
    let mutable _lastName : string = String.Empty
    let mutable _middleInitial : Char = ' '

    [<DataMember>]
    member public l.FirstName
        with get() = _firstName
        and set(value) = _firstName <- value

    [<DataMember>]
    member public l.LastName
        with get() = _lastName
        and set(value) = _lastName <- value

    [<DataMember>]
    member public l.MiddleInitial
        with get() = _middleInitial
        and set(value) = _middleInitial <- value

This was a straightforward translation from C# to F#. With Name type translation complete, you would expect the interface translation to be easy too, right? Let's look at what we have to do. We have two methods with the following signatures:

  • MyRequestReplyMessage takes a Name object and returns a string.
  • MyOneWayMessage takes an integer and a Boolean and returns nothing.

The literal translation to F# is as follows:

[<ServiceContract(Namespace=
    "http://www.scottseely.com/WCFDemo")>]
type ISimpleService =
    [<OperationContract>]
    abstract member MyRequestReplyMessage : Name -> string

    [<OperationContract(IsOneWay=true)>]
    abstract member MyOneWayMessage : int * bool -> unit

That code looks right, but it isn't. Further inspection shows that we're still missing some details. As you may recall, the data for MyRequestReplyMessage shows up in a parameter named fullName, and MyOneWayMessage has parameters named someInt and someBool. Where does that information live in the code above?

Answer: The information is missing. To fix this problem, we also need to name the F# parameters. This code gives names to the interface parameters:

[<ServiceContract(Namespace=
    "http://www.scottseely.com/WCFDemo")>]
type ISimpleService =
    [<OperationContract>]
    abstract member MyRequestReplyMessage : fullName : Name
        -> string

    [<OperationContract(IsOneWay=true)>]
    abstract member MyOneWayMessage : someInt : int *
        someBool : bool -> unit

To finish off our F# work, we need to define an implementation. We do this by defining a type that inherits from ISimpleService and implements the two methods in the interface:

type SimpleService() =
    interface ISimpleService with
        member x.MyRequestReplyMessage(fullName) =
            String.Format("{0} {1} {2}",
                fullName.FirstName,
                fullName.MiddleInitial,
                fullName.LastName)

        member x.MyOneWayMessage(someInt, someBool) =
            Debug.WriteLine(String.Format
                ("someInt: {0}, someBool: {1}",
                 someInt,
                 someBool))
            ()

It's important to note that the type has a parameterless constructor. You might define the type SimpleService as follows:

type SimpleService =

But in F#, you just defined a type that has no constructors, in which case WCF fails to instantiate the implementation because WCF relies on the contract implementation having a constructor that takes no parameters. On the other hand, if you type the following, F# generates a parameterless, do-nothing constructor:

type SimpleService() =

With that code written, we can turn to hosting the service.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus