WCF host Management Console. WindowsService. WinFrom. WebAPI host management console and windows service, and wcf host Management Console

Source: Internet
Author: User

WCF host Management Console. WindowsService. WinFrom. WebAPI host management console and windows service, and wcf host Management Console

Create the wcf Class Library first. Some Trial code will be generated by default:

Public class Service1

{

Public string GetData (int value)
{
Return string. Format ("You entered: {0}", value );
}

}

The code for the boarding console is as follows:

 

Using System. ServiceModel;

Using WcfServiceLibrary1;

 

ServiceHost serviceHost = new ServiceHost (typeof (Service1 ));
If (serviceHost. State! = CommunicationState. Opened)
{
ServiceHost. Open ();
}

Console. WriteLine ("the WCF Service is running ......");
Console. WriteLine ("ENTER the ENTER key <ENTER> exit the WCF Service ");
Console. ReadLine ();
ServiceHost. Close ();

 

The hostwinform is as follows:

Create a winform project. The form1 form is generated by default.

Using System. ComponentModel;
Using System. ServiceModel;

Using WcfServiceLibrary1;

ServiceHost serviceHost = null;
BackgroundWorker worker = null;

 

Public Form1 ()
{
InitializeComponent ();
Worker = new BackgroundWorker ();
Worker. RunWorkerCompleted + = new RunWorkerCompletedEventHandler (worker_RunWorkerCompleted );
Worker. DoWork + = new DoWorkEventHandler (worker_DoWork );

If (! Worker. IsBusy)
{
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. Result! = Null)
{
If (e. Result. ToString () = "normal ")
{
TssTips. Text = "the service is listening ......";
}
Else
{
TssTips. Text = string. Format ("error: {0}", e. Result );
}

LblTips. Text = tssTips. Text;
}
// Handle errors
}

 

Boarding WindowService

Add WindowService class library

Service1 is as follows:

Using System. ServiceModel;
Using System. ServiceProcess;

 

Protected override void OnStart (string [] args)
{
// TODO: Add code here to start the service.
Try
{
ServiceHost = new ServiceHost (typeof (WcfServiceLibrary1.Service1 ));
If (serviceHost. State! = CommunicationState. Opened)
{
ServiceHost. Open ();
}
}
Catch (Exception ex)
{
// LogTextHelper. Error (ex );
}

// LogTextHelper. Info (Constants. ServiceName + DateTime. Now. tow.timestring () + "the service is successfully called once. ");

// LogTextHelper. Info (Constants. ServiceName + "has been started successfully. ");
}

 

/*
Select service1 to add the installer
Select the serviceProcessInstaller1 component, view attributes, and set the account to LocalSystem.

Select the serviceInstaller1 component and view its attributes.
Set the ServiceName value, which indicates the name of the system service.
Set StartType. If it is Manual, it is manually started. The default value is stopped. If it is Automatic, it is automatically started.
Set Description and add service Description

Click Start and Enter cmd in the running process to obtain the command prompt.
Win7 must be started as an administrator; otherwise, it cannot be installed.

Enter cd C: \ Windows \ Microsoft. NET \ Framework \ v4.0.30319 and press Enter.
Switch the current directory. Note that in C: \ Windows \ Microsoft. there are many similar versions under the. NET \ Framework directory. The specific directory depends on the running environment of the project. For example. net framework2.0 requires entering cd C: \ Windows \ Microsoft. NET \ Framework \ v2.0.50727

Enter InstallUtil.exe D: \ G work \ WCF host WindowsService \ WcfServiceLibrary1 \ windowsservice \ bin \ Debug \ windowsservice.exe and press ENTER
Note: D: \ G work \ WCF host WindowsService \ WcfServiceLibrary1 \ windowsservice \ bin \ Debug \ windowsservice.exe shows the location of the exe file generated by the project.

Uninstalling is simple. Open cmd and enter SC delete WinServiceTest.
*/

If you want to test whether the WCF works properly

Create a console program. Right-click to add service reference

The IP address is as follows in the WCF Class Library:

<Service name = "WcfServiceLibrary1.Service1">
<Host>
<BaseAddresses>
<Add baseAddress = "http: // localhost: 8733/Design_Time_Addresses/WcfServiceLibrary1/Service1/"/>
</BaseAddresses>
</Host>

 

Next is the WEBAPI host.

 

Compared with WCF, WEBAPI uses the REST architecture and SOAP architecture. You can see that WEBAPI is lightweight when you select a host.

 

Create a console Program

Install SelfHost in nuget

Static void Main (string [] args)
{

Var config = new HttpSelfHostConfiguration ("http: // localhost: 8080 ");

Config. Routes. MapHttpRoute (
"API Default", "api/{controller}/{id }",
New {id = RouteParameter. Optional });

Using (HttpSelfHostServer server = new HttpSelfHostServer (config ))
{
Server. OpenAsync (). Wait ();
Console. WriteLine ("Press Enter to quit .");
Console. ReadLine ();
}
}

Public class Product
{
Public string Name {get; set ;}
Public string Price {get; set ;}
}
Public class ProductsController: ApiController
{
Static List <Product> products = new List <Product> (){
New Product () {Name = "product1", Price = "2.55 "},
New Product () {Name = "product2", Price = "2.3 "}
};
Public IEnumerable <Product> Get ()
{
Return products;
}
}

You can use the address bar or Ajax

The address bar is as follows:

Http: // localhost: 8080/api/products/

 

Here, we find that you only need to register the route and then write a controller to complete the WEBAPI function. It is very lightweight.

 

 

Create a Windows Service

 

Install SelfHost

Using System. ServiceProcess;
Using System. Web. Http;
Using System. Web. Http. SelfHost;

 

The code in WindowService. Service is as follows:

Public partial class Service1: ServiceBase
{

Private HttpSelfHostServer _ server;
Private readonly HttpSelfHostConfiguration _ config;
Public const string ServiceAddress = "http: // localhost: 1345 ";

Public Service1 ()
{
InitializeComponent ();
_ Config = new HttpSelfHostConfiguration (ServiceAddress );
_ Config. Routes. MapHttpRoute ("DefaultApi ",
"Api/{controller}/{id }",
New {id = RouteParameter. Optional });
}

Protected override void OnStart (string [] args)
{

# Region Web Api listener
_ Server = new HttpSelfHostServer (_ config );
_ Server. OpenAsync ();
# Endregion

}

Protected override void OnStop ()
{
_ Server. CloseAsync (). Wait ();
_ Server. Dispose ();
}

Public class ApiServiceController: ApiController
{
[HttpGet]
Public string Get ()
{
Return "Hello from windows service! ";
}
}

}

Http: // localhost: 1345/api/products/ApiService

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.