Chapter 4: WCF Hosting (2)

Original: http://www.wcftutorial.net/Introduction-to-WCF.aspx

Self-hosted Self Hosting

If it is a web service, we can only host the service on IIS, but WCF provides a service that can be hosted on any application (such as console applications, Windows Forms, etc.). Many interesting developers are responsible for providing and managing the lifecycle of managed processes. Server and client can exist in the same process at the same time. Now, let's create a WCF service hosted in a console application. We will create a proxy based on the abstract class ClientBase.

Note: The hosting program must run before client access, which also means you have to pre-launch it.

Step1: Let's start by creating the service July and its implementation. Create a console application and name it MyCalculatorService. This is a simple service that just returns the sum of the two numbers you want to add.



Step 2: Add the System.ServiceModel reference



Step 3: Create the ISimpleCalculator interface, add ServiceContract and OperationContract to the classes and methods, you will learn about their functions in the following content. These Attributes will advertise the service to the caller.

IMyCalculatorService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace MyCalculatorService
{
    [ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
}


Step 4: As shown below, MyCalculatorService is the implementation class of the IMyCalculatorService interface

MyCalculatorService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyCalculatorService
{
    class SimpleCalculator : ISimpleCalculator
    {
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }
    }
}


Step 5: Now that the service is ready, let's start implementing the hosting process, creating a new console application MyCalculatorServiceHost



Step 6: ServiceHost is the core class for hosting WCF services. Its constructor can accept the implemented contract class and service address as parameters. You can register multiple base addresses separated by commas, but the addresses must be based on the same transport protocol (http, etc.)

Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");

Uri tcpUrl = new Uri("net.tcp://localhost:8090/MyService/SimpleCalculator");

ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl, tcpUrl);


Multiple endpoints can be added using AddServiceEndpoint(). host.Open() will start the service, after which it is ready to serve clients.

Step 7: The following procedure illustrates how to implement a managed process

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace MyCalculatorServiceHost
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
            //Create ServiceHost
            ServiceHost host
            = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
            //Add a service endpoint
            host.AddServiceEndpoint(typeof(MyCalculatorService.ISimpleCalculator)
            , new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);
            //Start the Service
            host.Open();

            Console.WriteLine("Service is host at " + DateTime.Now.ToString());
            Console.WriteLine("Host is running... Press <Enter> key to stop");
            Console.ReadLine();
        }
    }
}


Step 8: Once the service has been managed and started, we can create the bringer class for the client service. There are different ways to create the
    proxy 1. Use SvcUtil.exe to create the proxy and associated configuration file
    2. Add the service reference to Client program
    3. Implement the base class ClientBase<T>
In these methods, it is the best practice to implement ClientBase<T>. If you use the other two, you need to create the proxy class every time when the service implementation changes. But using ClientBase<T> is not needed. It creates the proxy on startup, so it can handle any changes.

MyCalculatorServiceProxy.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using MyCalculatorService;
namespace MyCalculatorServiceProxy
{
    public class MyCalculatorServiceProxy :
        //WCF create proxy for ISimpleCalculator using ClientBase
        ClientBase<ISimpleCalculator>,
        ISimpleCalculator
    {
        public int Add(int num1, int num2)
        {
            //Call base to do funtion
            return base.Channel.Add(num1, num2);
        }
    }
}


Step 9: On the client side, we create an instance of the proxy class and use the following method call to add the reference to the proxy dll to the project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace MyCalculatorServiceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy ;
            proxy= new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
            Console.WriteLine("Client is running at " + DateTime.Now.ToString());
            Console.WriteLine("Sum of two numbers... 5+5 ="+proxy.Add(5,5));
            Console.ReadLine();
        }
    }
}


Step 10 : The endpoint information needs to be added to the configuration file of the client program.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <client>
            <endpoint address ="http://localhost:8090/MyService/SimpleCalculator"
                    binding ="wsHttpBinding"
                    contract ="MyCalculatorService.ISimpleCalculator">
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>


Step 11: Before running the client, you need to start the server first. The output of the client is as follows.



Self-hosting demonstrates the benefits of in-Pro hosting. Programmatically accessible, and can be programmed as a singleton service. You will love the self-hosting approach, now let's move on to the next step, hosting the service in the Windows Activation service.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326801481&siteId=291194637