I was trying to create a WCF Service Library in order to get more familiar with WCF. When I created a WCF Service Library project, a Class1.cs file was created.
This file has an interface and a public class that implements the interface. Basically just by creating a WCF Service Library project you get a WCF Service example. What’s good about this example, is that if you are new to this, you can use this example as a guideline to create your own WCF Service. I’m going to explain the file created by visual studio.
Class1.cs
using System.ServiceModel;
[ServiceContract()]
public interface IService1
{
[OperationContract]
string MyOperation1(string myValue);
[OperationContract]
string MyOperation2(DataContract1 dataContractValue);
}
If you noticed before the interface it says [ServiceContract()]. According to MSDN this is “a collection of Operations that specifies what the Endpoint” (when 2 entities are transferring data, the endpoint is the name for an entity on one end of the transfer ) “communicates to the outside world. Each operation is a simple message exchange.”
So basically the outside world is only going to be able to communicate with the methods MyOperation1 and MyOperation2 in this WCF Service. This methods need to be annotated with the attribute [OperationContract]. This is because they are methods of the service.
The implementation of the interface is
public class service1 : IService1
{
public string MyOperation1(string myValue)
{
return "Hello: " + myValue;
}
public string MyOperation2(DataContract1 dataContractValue)
{
return "Hello: " + dataContractValue.FirstName;
}
}
This class is very straightforward, it inherits an interface, and implements the methods of the interface. However if you notice the method MyOperation2 receives a DataContract1 parameter. This is a class this file created by visual studio also provides. I’ll show the code of this class and explain some interesting things about the class.
[DataContract]
public class DataContract1
{
string firstName;
string lastName;
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
Before the class definition there is something like this [DataContract]. According to MSDN “a data contract is an abstract description of a set of fields with a name and data type for each field”. In this case the set of fields of the class will be firstName and lastName, the data type will be string. In this class only properties that include [DataMember] will be accessed.