Tomasz Rabiński | zavaz Blog
C# SharePoint VSTO
Hosting WCF service in a console application
- IIS
- WAS
- Windows service
- console application
First, create a new WCF Service Appliaction project. Then open the IService1.cs interface and add a custom method:
1
2
| [OperationContract] int GetSum(int a, int b); |
1
2
3
4
| public int GetSum(int a, int b) { return a + b; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| //Creating a new ServiceHost instance with two base addresses: one for the http and second for the net.tcp using (ServiceHost sh = new ServiceHost(typeof(WCFAppTest.Service.Service1), new Uri("http://localhost:72/Service"), new Uri("net.tcp://localhost:71/Service"))) { //Adding the endpoints to the ServiceHost sh.AddServiceEndpoint(typeof(WCFAppTest.Service.IService1), new NetTcpBinding(), ""); sh.AddServiceEndpoint(typeof(WCFAppTest.Service.IService1), new WSHttpBinding(), ""); //Creating a new Service Behavior ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; sh.Description.Behaviors.Add(smb); //Opening the ServiceHost for incoming connections sh.Open(); System.Console.WriteLine("Waiting for connections..."); System.Console.ReadLine(); //Close opened ServiceHost object sh.Close(); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| using (ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client()) { proxy.Endpoint.Address = new System.ServiceModel.EndpointAddress(new Uri("net.tcp://localhost:71/Service")); proxy.Endpoint.Binding = new NetTcpBinding(); proxy.Endpoint.Contract.ContractType = typeof(WCFAppTest.Service.IService1); Console.WriteLine("Net.TCP: 1 + 1 is " + proxy.GetSum(1, 1)); proxy.Close(); } using (ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client()) { proxy.Endpoint.Address = new System.ServiceModel.EndpointAddress(new Uri("http://localhost:72/Service")); proxy.Endpoint.Binding = new WSHttpBinding(); proxy.Endpoint.Contract.ContractType = typeof(WCFAppTest.Service.IService1); Console.WriteLine("HTTP: 2 + 2 is " + proxy.GetSum(2, 2)); proxy.Close(); } Console.ReadLine(); |
OK, now You can run first the service console app and then the test console app and You should see the results like this:
No comments:
Post a Comment