Dela via


Anvisningar: Ange en klientbindning i konfigurationen

I det här exemplet skapas ett klientkonsolprogram för att använda en kalkylatortjänst och bindningen för klienten anges deklarativt i konfigurationen. Klienten kommer åt CalculatorService, som implementerar ICalculator gränssnittet, och både tjänsten och klienten använder BasicHttpBinding klassen.

Proceduren som beskrivs förutsätter att kalkylatortjänsten körs. Information om hur du skapar tjänsten finns i Så här anger du en tjänstbindning i konfigurationen. Den använder också verktyget ServiceModel Metadata Utility (Svcutil.exe) som Windows Communication Foundation (WCF) tillhandahåller för att automatiskt generera klientkomponenterna. Verktyget genererar klientkoden och konfigurationen för åtkomst till tjänsten.

Klienten är inbyggd i två delar. Svcutil.exe genererar ClientCalculator det som implementerar ICalculator gränssnittet. Det här klientprogrammet konstrueras sedan genom att skapa en instans av ClientCalculator.

Det är vanligtvis bästa praxis att ange bindnings- och adressinformationen deklarativt i konfigurationen snarare än att absolut i kod. Det är vanligtvis inte praktiskt att definiera slutpunkter i kod eftersom bindningar och adresser för en distribuerad tjänst vanligtvis skiljer sig från de som används när tjänsten utvecklas. Mer allmänt gör det möjligt för dem att ändra bindningen och adresseringsinformationen utan att behöva kompilera om eller distribuera om programmet.

Du kan utföra alla följande konfigurationssteg med hjälp av konfigurationsredigeraren (SvcConfigEditor.exe).

Källkopian av det här exemplet finns i BasicBinding-exemplet .

Ange en klientbindning i konfigurationen

  1. Använd Svcutil.exe från kommandoraden för att generera kod från tjänstmetadata.

    Svcutil.exe <service's Metadata Exchange (MEX) address or HTTP GET address>
    
  2. Klienten som genereras innehåller det ICalculator gränssnitt som definierar tjänstkontraktet som klientimplementeringen måste uppfylla.

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(Namespace="http://Microsoft.ServiceModel.Samples", ConfigurationName="Microsoft.ServiceModel.Samples.ICalculator")]
    public interface ICalculator
    {
    
        [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Add", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/AddResponse")]
        double Add(double n1, double n2);
    
        [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Subtract", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/SubtractResponse")]
        double Subtract(double n1, double n2);
    
        [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Multiply", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/MultiplyResponse")]
        double Multiply(double n1, double n2);
    
        [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Samples/ICalculator/Divide", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/DivideResponse")]
        double Divide(double n1, double n2);
    }
    
    [ServiceContract]
    public interface ICalculator
    {
       [OperationContract]
       double Add(double n1, double n2);
       [OperationContract]
       double Subtract(double n1, double n2);
       [OperationContract]
       double Multiply(double n1, double n2);
       [OperationContract]
       double Divide(double n1, double n2);
    }
    
    
  3. Den genererade klienten innehåller också implementeringen av ClientCalculator.

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public partial class CalculatorClient : System.ServiceModel.ClientBase<Microsoft.ServiceModel.Samples.ICalculator>, Microsoft.ServiceModel.Samples.ICalculator
    {
    
        public CalculatorClient()
        {
        }
    
        public CalculatorClient(string endpointConfigurationName) :
                base(endpointConfigurationName)
        {
        }
    
        public CalculatorClient(string endpointConfigurationName, string remoteAddress) :
                base(endpointConfigurationName, remoteAddress)
        {
        }
    
        public CalculatorClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
                base(endpointConfigurationName, remoteAddress)
        {
        }
    
        public CalculatorClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
                base(binding, remoteAddress)
        {
        }
    
        public double Add(double n1, double n2)
        {
            return base.Channel.Add(n1, n2);
        }
    
        public double Subtract(double n1, double n2)
        {
            return base.Channel.Subtract(n1, n2);
        }
    
        public double Multiply(double n1, double n2)
        {
            return base.Channel.Multiply(n1, n2);
        }
    
        public double Divide(double n1, double n2)
        {
            return base.Channel.Divide(n1, n2);
        }
    }
    
    public class CalculatorService : ICalculator
    {
       public double Add(double n1, double n2)
       {
          return n1 + n2;
       }
       public double Subtract(double n1, double n2)
       {
          return n1 - n2;
       }
       public double Multiply(double n1, double n2)
       {
          return n1 * n2;
       }
       public double Divide(double n1, double n2)
       {
          return n1 / n2;
       }
    }
    
    
  4. Svcutil.exe genererar också konfigurationen för klienten som använder BasicHttpBinding klassen. När du använder Visual Studio, namnge den här filen App.config. Observera att adress- och bindningsinformationen inte anges någonstans i implementeringen av tjänsten. Dessutom behöver koden inte skrivas för att hämta den informationen från konfigurationsfilen.

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>
    
        <client>
          <endpoint 
              name=""
              address="http://localhost/servicemodelsamples/service.svc" 
              binding="basicHttpBinding" 
              contract="Microsoft.ServiceModel.Samples.ICalculator" />
        </client>
    
        <bindings>
          <basicHttpBinding/>
        </bindings>
    
      </system.serviceModel>
    
    </configuration>
    
  5. Skapa en instans av ClientCalculator i ett program och anropa sedan tjänståtgärderna.

    
    using System;
    using System.ServiceModel;
    
    namespace Microsoft.ServiceModel.Samples
    {
    
        //Client implementation code.
        class Client
        {
            static void Main()
            {
                // Create a client with given client endpoint configuration
                CalculatorClient client = new CalculatorClient();
    
                // Call the Add service operation.
                double value1 = 100.00D;
                double value2 = 15.99D;
                double result = client.Add(value1, value2);
                Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
    
                // Call the Subtract service operation.
                value1 = 145.00D;
                value2 = 76.54D;
                result = client.Subtract(value1, value2);
                Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);
    
                // Call the Multiply service operation.
                value1 = 9.00D;
                value2 = 81.25D;
                result = client.Multiply(value1, value2);
                Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);
    
                // Call the Divide service operation.
                value1 = 22.00D;
                value2 = 7.00D;
                result = client.Divide(value1, value2);
                Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);
    
                //Closing the client gracefully closes the connection and cleans up resources
                client.Close();
    
                Console.WriteLine();
                Console.WriteLine("Press <ENTER> to terminate client.");
                Console.ReadLine();
            }
        }
    }
    
    
  6. Kompilera och kör klienten.

Se även