Sunday, April 9, 2017

C# code snippet for creating a self hosted WCF service

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 ServiceHost employeeServiceHost = null;
            try
            {
                //Base Address for EmployeeService
                Uri httpBaseAddress = new Uri("http://localhost:8080/EmployeeService");
                
                //Instantiate ServiceHost
                employeeServiceHost = new ServiceHost(typeof(Employee.EmployeeService),httpBaseAddress); 
 
               //Add Endpoint to Host
                employeeServiceHost.AddServiceEndpoint(typeof(EmployeeService.IEmployeeService),new WSHttpBinding(), "");            
 
               //Metadata Exchange
                ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
                serviceBehavior.HttpGetEnabled = true;
                employeeServiceHost.Description.Behaviors.Add(serviceBehavior);
 
                //Open
                employeeServiceHost.Open();
                Console.WriteLine("Employee Service is listening at : {0}", httpBaseAddress);
                Console.ReadKey();                
            }
            catch (Exception ex)
            {
                employeeServiceHost = null;
                Console.WriteLine(" An error occurred with EmployeeService" + ex.Message);
            }