Articles → WCF → Hosting WCF Using Console Application
Hosting WCF Using Console Application
Software Requirement
Prerequisite Knowledge
- What is WCF service?
- What is a service contract?
- What is an operation contract?
- How to create projects using visual studio?
Steps Of Execution
- Create a WCF service
- Create a console application for hosting service
- Create a console client application
Create A WCF Service
Click to Enlarge
using System.ServiceModel;
namespace WCFService {
[ServiceContract(Name = "MyService", Namespace = "MyNamespace")]
public interface IHello {
[OperationContract(Name = "HelloMethod")]
string SayHello(string name);
}
}
namespace WCFService {
public class Hello: IHello {
public string SayHello(string name) {
return string.Format("Hello {0}", name);
}
}
}
Create A Console Application For Hosting Service
Click to Enlarge
using System;
using System.ServiceModel;
namespace HostingServer {
class Program {
static void Main(string[] args) {
ServiceHost host = new ServiceHost(typeof(WCFService.Hello));
host.Open();
Console.ReadLine();
host.Close();
}
}
}
<?xml version="1.0" encoding="utf-8" ?><configuration><system.serviceModel><services><service name="WCFService.Hello" behaviorConfiguration="MyBehavior"><host><baseAddresses><add baseAddress="http://localhost:9876/serviceURL"/></baseAddresses></host><endpoint address="" binding="basicHttpBinding" contract="WCFService.IHello"></endpoint><endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint></service></services><behaviors><serviceBehaviors><behavior name="MyBehavior"><serviceMetadata/></behavior></serviceBehaviors></behaviors></system.serviceModel></configuration>
Create A Console Client Application
- Right click of the console application HostingServer and set the project as start up project
- Press Ctrl + F5 to run the application. See the screen shot below
Click to Enlarge
- Now right click on the client console application and click on Add Service Reference…
- A pop up appears. Inside the Address textbox add the base address which we have added in app.config file of hostingServer console application i.e. http://localhost:9876/serviceURL..
- Click on Go. See the screen shot below
Click to Enlarge
- Once you find the service click on Ok. A service reference is added in the project.
using System;
namespace ClientApp {
class Program {
static void Main(string[] args) {
ServiceReference1.MyServiceClient proxy = new ServiceReference1.MyServiceClient();
Console.WriteLine(proxy.HelloMethod("Karan"));
Console.ReadLine();
}
}
}
Output
Click to Enlarge
- Click on the service reference in the client console application
- Click on Show all files.
- Expand the service reference
- Expand the file Reference.svcmap and click on reference.cs. See the screen shot below for proxy class.
Click to Enlarge