using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
namespace WCFTest
{
///<summary>
/// A data contract stores some data and allows it to be serialised for passing to OperationContract's
///</summary>
[DataContract]
class Thing
{
///<summary>
/// Some data that will be filled.
/// This can be a property and the getter and setter will be called on it when it is filled with data.
///</summary>
[DataMember]
public string SomeData = "";
}
[ServiceContract]
interface IDoStuff
{
///<summary>
/// Jump method
///</summary>
[OperationContract]
void Jump();
///<summary>
/// Duck method
///</summary>
[OperationContract]
void Duck();
///<summary>
/// Hide method
///</summary>
///<param name="thingy">A parameter DataContract to be passed</param>
[OperationContract]
void Hide(Thing thingy);
}
///<summary>
/// This is the class that provides the actual code to do the work, it conforms to the contract defined earlier.
///</summary>
class StuffWorker : IDoStuff
{
#region IDoStuff Members
///<summary>
/// The jump method, with code
///</summary>
public void Jump()
{
Console.WriteLine("Jump: Remote method executing here.");
}
///<summary>
/// The duck method with code
///</summary>
public void Duck()
{
Console.WriteLine("Duck: Another remote method executing here.");
}
///<summary>
/// Hide something method
///</summary>
///<param name="thingy">The item to hide</param>
public void Hide(Thing thingy)
{
Console.WriteLine("Hiding: Remote method is hiding " + thingy.SomeData);
}
#endregion
}
///<summary>
/// A self hosting WCF service that does not use the configuration file
///</summary>
class Program
{
///<summary>
/// Program start
///</summary>
///<param name="args"></param>
static void Main(string[] args)
{
Console.Write("Starting the service...");
ServiceHost host = start();
Console.WriteLine("Ok");
Console.ReadKey();
}
static ServiceHost start()
{
//this does the hosting
ServiceHost host = new ServiceHost(typeof(StuffWorker), new Uri("http://localhost:7000/WCF/"));
//this lets you browse to the WSDL:
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.HttpGetUrl = new Uri("http://localhost:7000/WCF/Meta");
host.Description.Behaviors.Add(smb);
//This is the bit that handles HTTP
WSHttpBinding ws = new WSHttpBinding(SecurityMode.None);
Binding mex = MetadataExchangeBindings.CreateMexHttpBinding();
//These are the endpoints on that HTTP server
host.AddServiceEndpoint("WCFTest.IDoStuff", ws, "http://localhost:7000/WCF/DoStuff"); //one to actually do things
host.AddServiceEndpoint(typeof(IMetadataExchange), mex, "http://localhost:7000/WCF/Meta"); //and one to provide metadata
// start listening
host.Open();
return host;
}
}
}
A self hosting service example mostly so I don't forget how. Remember to add references to System.ServiceModel and System.Runtime.Serialisation!
Permalink 3 Comments