Several ways to host Microsoft WCF, homestay IIS, Homestay WinForm, hosted consoles, hosted Windows services

Source: Internet
Author: User
Tags hosting web hosting

WCF boarding is a very flexible operation that can be hosted in IIS services, Windows Services, WinForm programs, and console programs, enabling the operation of the WCF service and providing a convenient and efficient service invocation for the caller. This article describes these methods in detail and develops examples to illustrate the way in which WCF homestay is fully understood.

1. IIS Service homestay for WCF services

I'm in front of me. A few introductory articles in the WCF development framework describe a common way to host WCF, which is hosted by IIS services. This kind of boarding is the most convenient way, and it is widely used because the service only needs to be run automatically by IIS.

To create this way of IIS boarding, simply add the WCF service application inside the solution, and you can generate this kind of service module.

This is a Web-based application that creates a SERVICE1.SVC service page after the project is created, as well as the associated WCF service interface and implementation, as shown in.

This is a simple WCF service, of course, if it is a complex practical application, it will consider working with the database, and perhaps the project will be divided into several to manage, for better logical separation operations.

2. Create a WCF service library to prepare for multiple boarders

In addition to the above commonly used IIS service homestay, there will generally be a variety of boarding methods, but if the other way of boarding, generally will be the WCF services and boarding method of the project separation, to achieve better reuse operations, especially WCF needs to consider a variety of boarding methods. Here's an introduction to the WCF Service Library and WCF service applications, and let's look at the basics.

The WCF service Library, which can be thought of as a class library that contains WCF services and contract definitions. The WCF Service Library is not yet ready to run directly, you can reference it in other projects and enable hosting this library in the host.

While a WCF application is a program that can execute, it has a separate process, and the WCF service class contract definition can be directly seen running effect. This project template should be an IIS-managed program.

The former generally consider WCF service design, the service class is defined as a separate library, can be used for other projects. Improve the reusability of your code. The latter is more common when developing an IIS-hosted WCF service program, and can be used on a self-study basis. Of course you can also modify the code, such as moving a class from a WCF service program to a separate class library.

Create a WCF service library that you can understand for us to develop. NET program when creating a class library module that does not contain an interface, as shown below, creates a WCF service library.

Once determined, there is only one sample service Service1 generated.

Here, we do not modify any of their code for demonstration purposes, as shown in the original code.

Using system;using system.collections.generic;using system.linq;using system.runtime.serialization;using system.servicemodel;using system.text;namespace wcfservicelibrary{Public    class Service1:iservice1    {        public string GetData (int value)        {            return string. Format ("you entered: {0}", value);        }        Public Compositetype getdatausingdatacontract (Compositetype composite)        {            if (composite = = null)            {                throw new ArgumentNullException ("composite");            }            if (composite. Boolvalue)            {                composite. StringValue + = "Suffix";            }            return composite;}}    }
3. Host of the WCF Services console program

This is also a common way of hosting WCF services, by launching a DOS-like window console software, to implement the dynamic hosting of WCF services, close the console program, the service terminates naturally.

This is simple, create a console program, and then add the WCF Service Class library project application, add the following code in the main function to implement.

Namespace wcfservice_hostconsole{    class program    {        static void Main (string[] args)        {                        try            {                ServiceHost ServiceHost = new ServiceHost (typeof (Service1));                if (servicehost.state! = communicationstate.opened)                {                    servicehost.open ();                }                Console.WriteLine ("WCF service is running ...");                Console.WriteLine ("Input enter key <ENTER> exit WCF service");                Console.ReadLine ();                Servicehost.close ();            }            catch (Exception ex)            {                Console.WriteLine (ex);            }        }    }

4. WinForm program hosting for WCF services

As with the console program, we create a WinForm project and then add the hosted code to the form startup code, and for a better response experience, you can use the background threading program to start the service, as shown below.

namespace wcfservice_hostwinform{public partial class Frmmain:form {ServiceHost ServiceHost = null;        BackgroundWorker worker = null;            Public Frmmain () {InitializeComponent ();            Worker = new BackgroundWorker (); Worker.            runworkercompleted + = new Runworkercompletedeventhandler (worker_runworkercompleted); Worker.            DoWork + = new Doworkeventhandler (worker_dowork); if (!worker.                IsBusy) {Tsstips.text = "starting ...";                Lbltips.text = Tsstips.text; Worker.            RunWorkerAsync ();                }} void Worker_dowork (object sender, DoWorkEventArgs e) {try {                ServiceHost = new ServiceHost (typeof (Service1));                if (servicehost.state! = communicationstate.opened) {servicehost.open ();            } E.result = "normal"; } catch (Exception ex) {e.result = ex.            Message; }} void Worker_runworkercompleted (object sender, Runworkercompletedeventargs e) {if (E.R Esult! = null) {if (e.result.tostring () = = "Normal") {Tsstips.te                XT = "Service is listening ..."; } else {Tsstips.text = string.                Format ("error: {0}", E.result);            } lbltips.text = Tsstips.text; }        }        ...........................    }}

Of course, in order to prevent the WinForm program is accidentally closed, you can add the tray code, the program to reduce the tray icon inside.

5. The Windows Service program hosted by WCF services

This way of service boarding, and IIS have the same advantages, the system starts, the WCF service will follow the start, without human intervention, but also a good way to host.

In order to implement this way of lodging, we create a console program and then add the response to the window service and the installer class

Then add the WCF boarding code to the service class startup, as shown below.

 public class Servicemanager:servicebase {private static object syncRoot = new Object ();//Sync Lock Private ServiceHost ServiceHost = null; Host service object Public ServiceManager () {this.        ServiceName = Constants.servicename;        }///<summary>///Set up a specific action so that the service can perform its work.                </summary> protected override void OnStart (string[] args) {try {                ServiceHost = new ServiceHost (typeof (Service1));                if (servicehost.state! = communicationstate.opened) {servicehost.open ();            }} catch (Exception ex) {logtexthelper.error (ex); } logtexthelper.info (Constants.servicename + DateTime.Now.ToShortTimeString () + "service was successfully invoked once.            "); Logtexthelper.info (Constants.servicename + "has successfully started.)        "); }

In order to implement parameterized installation and uninstallation services through this console program, we need to intercept the parameters of the console and perform the appropriate operations as shown below.

        <summary>///The main entry point of the application. </summary> [STAThread] static void Main (string[] args) {ServiceController servi            CE = new ServiceController (constants.servicename); Run the service if (args.                Length = = 0) {servicebase[] servicestorun;                ServicesToRun = new servicebase[] {new ServiceManager ()};            Servicebase.run (ServicesToRun); } else if (Args[0]. ToLower () = = "/I" | | Args[0]. ToLower () = = "-i") {#region installation service if (!                        Serviceisexisted (Constants.servicename)) {try {                        String[] CmdLine = {}; String servicefilename = System.Reflection.Assembly.GetExecutingAssembly ().                        Location;                        Transactedinstaller Transactedinstaller = new Transactedinstaller (); Assemblyinstaller Assemblyinstaller = new Assemblyinstaller (Servicefilename, cmdline);                        TRANSACTEDINSTALLER.INSTALLERS.ADD (Assemblyinstaller);                        Transactedinstaller.install (New System.Collections.Hashtable ());                        TimeSpan Timeout = timespan.frommilliseconds (1000 * 10); Service.                        Start (); Service.                    WaitForStatus (servicecontrollerstatus.running, timeout);                        } catch (Exception ex) {logtexthelper.info (ex);                    Throw }} #endregion} else if (Args[0]. ToLower () = = "U" | | Args[0]. ToLower () = = "-U") {#region Delete service try {if (Ser                        Viceisexisted (Constants.servicename)) {string[] cmdline = {}; String ServiCefilename = System.Reflection.Assembly.GetExecutingAssembly ().                        Location;                        Transactedinstaller Transactedinstaller = new Transactedinstaller ();                        Assemblyinstaller Assemblyinstaller = new Assemblyinstaller (Servicefilename, cmdline);                        TRANSACTEDINSTALLER.INSTALLERS.ADD (Assemblyinstaller);                    Transactedinstaller.uninstall (NULL);                    }} catch (Exception ex) {logtexthelper.info (ex);                Throw } #endregion}}

After the compiler succeeds, we add two batches of DOS scripts to automate the installation and uninstallation of the execution program, as shown below.

Installation scripts

"Wcfservice_hostwinservice.exe"-ipause

Unload script

"Wcfservice_hostwinservice.exe"-upause

After the script executes successfully, a service item is added to the list of services.

Uninstall the operation, directly execute the script will uninstall the service, very convenient oh.

6. Web Hosting for WCF services

Of course, in addition to the above several ways, this way in the WCF Service Library can also be hosted in the Web (IIS mode), this way is more simple, add a suffix name of the Svc file, only need a line of code, as follows.

7. Enable WCF services to support get-mode calls

Sometimes, we may publish a service through a small program for the sake of need, and then make calls to other programs, either the Web or WinForm, but we want to provide a call based on http,get or post to implement the interface, for example, Provides a JSON-formatted or text-formatted content return operation.

If it is integrated in WinForm, then we add a WCF item inside the WinForm, modify the code inside it, as shown below.

The first thing to add is a description of the WCF service interface that uses get mode. If it is POS mode, the increase setting is a bit different ([WebInvoke (Method = "POST", bodystyle = webmessagebodystyle.wrapped, Responseformat = Webmessageformat.json)]).

namespace wcfserviceforwinform{    [ServiceContract] public    interface IService1    {        [operationcontract ]        void DoWork ();        [OperationContract]         = "GET", Responseformat = Webmessageformat.json)]        [string GetData (int value);}    }

Second, add the appropriate settings to the implementation class

namespace wcfserviceforwinform{    = aspnetcompatibilityrequirementsmode.allowed)]    Public Class Service1:iservice1    {public        void DoWork ()        {        } public        string GetData (int value)        {            return string. Format ("you entered: {0}", value);}}}    

The configuration file is shown below, with special attention to color labeling:

<?xml version= "1.0"?><configuration> <system.web> <compilation debug= "true"/> </ system.web> <system.serviceModel> <services> <service name= "Wcfserviceforwinform.service1" Beh aviorconfiguration= "ServiceConfig" > <endpoint address= "" binding= "WebHttpBinding" Bindingcon figuration= "Webhttpbindingwithjsonp" behaviorconfiguration= "WebHttpBehavior" contract= "WcfServiceForWinfo Rm. IService1 "> </endpoint> <endpoint address=" Mex "binding=" mexHttpBinding "contract=" Imetadataexch Ange "/> 

After running the WinForm program and starting the WCF service, we can operate on the browser (Chrome), as shown in the following results.

From what we can see, this WCF service is started by WinForm, the connection can also be called by the Get method, the interface can be passed through parameters, and for some interfaces, such as JSON interface, which is convenient to transmit data, it is a very convenient call.

Several ways to host Microsoft WCF, homestay IIS, Homestay WinForm, hosted consoles, hosted Windows services

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.