Eksportér (0) Udskriv
Udvid alt
EN
Dette indhold er ikke tilgængeligt på dit sprog, men her er den engelske version.

Step 4: Host and Run a Basic Web Service to Register with Service Bus

Updated: June 18, 2014

This is the fourth of seven tasks required to create a basic Service Bus service application and a client that can call the service. For an overview of all six of the tasks, see the Service Bus Relayed Messaging Tutorial topic. This topic describes how to run a basic Service Bus service.

A complete listing of the code written in this task is provided in the example following the procedure.

Estimated time to completion: 10 minutes

To create the Service Bus credentials

  1. Add a reference to Microsoft.ServiceBus.dll to the project:

    1. In Solution Explorer, right-click References under the project folder and then click Add Reference.

    2. Select the .NET tab in the Add Reference dialog and scroll down until you see Microsoft.ServiceBus. Or, click Browse and navigate to the assembly on your hard drive. Typically, this is located in Program Files\<sdkInstallDirectory>\v1.0\Assemblies\NET4.0. Select the Microsoft.ServiceBus assembly, then click OK.

    noteNote
    When using a command-line compiler (for example, Csc.exe), you must also provide the path to the assemblies.

  2. In Program.cs, add a using statement for the Microsoft.ServiceBus namespace.

    using Microsoft.ServiceBus;
    

    Microsoft.ServiceBus is the namespace containing APIs that let you programmatically access many of the core features of Service Bus. You will most likely use this namespace in all your Service Bus applications.

  3. In the Main() method, create three variables in which to store the service namespace, issuer name, and issuer secret (a name/password credential) that are read from the console window.

    Console.Write("Your Service Namespace: ");
    string serviceNamespace = Console.ReadLine();
    Console.Write("Your Issuer Name: ");
    string issuerName = Console.ReadLine();
    Console.Write("Your Issuer Secret: ");
    string issuerSecret = Console.ReadLine();
    

    The issuer name and issuer secret will be used later to access your Service Bus project. The service namespace is passed as a parameter to CreateServiceUri to create a service URI.

  4. Using a TransportClientEndpointBehavior object, declare that you will be using a shared secret as the credential type. Add the following code directly underneath the code added in the last step.

    TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
    sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);
    

To create a base address for the service

  1. Following the code you added in the last step, create a Uri instance for the base address of the service. This URI specifies the Service Bus scheme, the service namespace, and the path of the service interface.

    Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "EchoService");
    

    “sb” is an abbreviation for the Service Bus scheme, and indicates that we are using TCP as the protocol. This was also previously indicated in the configuration file, when NetTcpRelayBinding was specified as the binding.

    For this tutorial, the URI is sb://putServiceNamespaceHere.windows.net/EchoService.

To create and configure the service host

  1. Set the connectivity mode to AutoDetect.

    ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;
    

    The connectivity mode describes the protocol the service uses to communicate with Service Bus; either HTTP or TCP. Using the default setting AutoDetect, the service will attempt to connect to Service Bus over TCP if it is available, and HTTP if TCP is not available. Note that this differs from the protocol the service specifies for client communication. That protocol is determined by the binding used. For example, a service can use the BasicHttpRelayBinding binding, which specifies that its endpoint (exposed on Service Bus) communicates with clients over HTTP. That same service could specify ConnectivityMode.AutoDetect so that the service communicates with Service Bus over TCP.

  2. Create the service host, using the URI created earlier in this section.

    ServiceHost host = new ServiceHost(typeof(EchoService), address);
    

    The service host is the WCF object that instantiates the service. Here, you pass it the type of service you want to create (an EchoService type), and also to the address at which you want to expose the service.

  3. At the top of the Program.cs file, add references to System.ServiceModel.Description and Microsoft.ServiceBus.Description.

    using System.ServiceModel.Description;
    using Microsoft.ServiceBus.Description;
    
  4. Back in Main(), configure the endpoint to enable public access.

    IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);
    

    This step informs Service Bus that your application can be found publicly by examining the Service Bus ATOM feed for your project. If you set DiscoveryType to private, a client would still be able to access the service. However, the service would not appear when it searches the Service Bus namespace. Instead, the client would have to know the endpoint path beforehand. For more information, see Discovering and Exposing a Service Bus Service.

  5. Apply the service credentials to the service endpoints defined in the App.config file:

    foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
    {
        endpoint.Behaviors.Add(serviceRegistrySettings);
        endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
    }
    

    As stated in the previous step, you could have declared multiple services and endpoints in the configuration file. If you had, this code would traverse the configuration file and search for every endpoint to which it should apply your credentials. However, for this tutorial, the configuration file has only one endpoint.

To open the service host

  1. Open the service.

    host.Open();
    
  2. Inform the user that the service is running, and explain how to shut down the service.

    Console.WriteLine("Service address: " + address);
    Console.WriteLine("Press [Enter] to exit");
    Console.ReadLine();
    
  3. When finished, close the service host.

    host.Close();
    
  4. Press F6 to build the project.

Example

The following example includes the service contract and implementation from previous steps in the tutorial, and hosts the service in a console application. Compile the following into an executable named EchoService.exe.

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Description;

namespace Microsoft.ServiceBus.Samples
{
    [ServiceContract(Name = "IEchoContract", Namespace = "http://samples.microsoft.com/ServiceModel/Relay/")]

    public interface IEchoContract
    {
        [OperationContract]
        String Echo(string text);
    }

    public interface IEchoChannel : IEchoContract, IClientChannel { };

    [ServiceBehavior(Name = "EchoService", Namespace = "http://samples.microsoft.com/ServiceModel/Relay/")]

    class EchoService : IEchoContract
    {
        public string Echo(string text)
        {
            Console.WriteLine("Echoing: {0}", text);
            return text;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;

            
            
            Console.Write("Your Service Namespace: ");
            string serviceNamespace = Console.ReadLine();
            Console.Write("Your Issuer Name: ");
            string issuerName = Console.ReadLine();
            Console.Write("Your Issuer Secret: ");
            string issuerSecret = Console.ReadLine();

           // Create the credentials object for the endpoint.
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
            sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);


            // Create the service URI based on the service namespace.
            Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "EchoService");

            // Create the service host reading the configuration.
            ServiceHost host = new ServiceHost(typeof(EchoService), address);

            // Create the ServiceRegistrySettings behavior for the endpoint.
            IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

            // Add the Service Bus credentials to all endpoints specified in configuration.
            foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
            {
                endpoint.Behaviors.Add(serviceRegistrySettings);
                endpoint.Behaviors.Add(sharedSecretServiceBusCredential);
            }
            
            // Open the service.
            host.Open();

            Console.WriteLine("Service address: " + address);
            Console.WriteLine("Press [Enter] to exit");
            Console.ReadLine();

            // Close the service.
            host.Close();
        }
    }
}

Now that the interface is created, proceed to Step 5: Create a WCF Client for the Service Contract to implement the interface.

Fællesskabsindhold

Tilføj
Vis:
© 2014 Microsoft