Service boarding using a code-only approach
The purpose of the service homestay is to open a process that provides a running environment for the WCF service. By adding one or more endpoints to the service to expose it to potential service consumption, the service consumer invokes the service through a matching endpoint, removing the two boarding methods above, and implementing the service's boarding work in a purely code-based manner.
Create a new console application to add a reference to the System.ServiceModel library file.
Add WCF Service Interface: Ischool using ServiceContract for interface constraints, operationcontract behavior constraints
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.ServiceModel;6 usingSystem.ServiceModel.Activation;7 8 9 namespaceWcftest.demo3Ten { One [ServiceContract] A Public InterfaceIschool - { - [OperationContract] the stringShowName (stringName); - } -}
Add the school class to implement the Ishool interface:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 6 namespaceWcftest.demo37 {8 Public classSchool:ischool9 {Ten Public stringShowName (stringname) One { A return "Show Name"+name; - } - } the}
Host the Ischool interface to the console application via code:
1 class Program2 {3 Static voidMain (string[] args)4 {5 Corecodeopen ();6 }7 8 /// <summary>9 ///work through the code to complete the service's homestayTen /// </summary> One Static voidCorecodeopen () A { - Try - { the using(ServiceHost host =NewServiceHost (typeof(School))) - { -Host. AddServiceEndpoint (typeof(Ischool),NewWshttpbinding (),"Http://10.0.0.217:20004/School"); - if(host. description.behaviors.find<servicemetadatabehavior> () = =NULL) + { -ServiceMetadataBehavior behavior =NewServiceMetadataBehavior (); +Behavior. httpgetenabled =true; ABehavior. Httpgeturl =NewUri ("Http://10.0.0.217:20004/School/wcfapi"); at host. DESCRIPTION.BEHAVIORS.ADD (behavior); - } - host. Open (); -Console.WriteLine ("host to console applications, open WCF services through code"); - Console.readkey (); - } in } - Catch(Exception ex) to { +Console.WriteLine ("corecodeopen Error:"+Ex. Message); - } the } *}
View Code
Run Program as Administrator > enter http://10.0.0.217:20004/school/wcfapi> in the browser we will get to WSDL (Network Service Description Language-web Services Description Language) service metadata in the form of
Create a new console client in the solution, add a service reference, enter HTTP://10.0.0.217:20004/SCHOOL/WCFAPI
We found our Ischool service interface, and the invocation of the service after the reference was added.
Work with the code to complete the hosting of a WCF service