WCF 简单的应用

  服务契约:

namespace Contracts
{
    [System.ServiceModel.ServiceContract]
    public interface ICalculator
    {
        [System.ServiceModel.OperationContract]
        double Add(double ax, double bx);
    }
}

服务:

namespace Service
{
  public  class CalculatorService:ICalculator
    {
      public double Add(double ax, double bx)
      {
          return ax + bx;
      }
    }
}

 自我寄宿:

      using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
            {
                host.AddServiceEndpoint(typeof(ICalculator),
                    new WSHttpBinding(),
                    "http://127.0.0.1:8888/calculatorservice");
                if(host.Description.Behaviors.Find<ServiceMetadataBehavior>()==null)
                {
                    ServiceMetadataBehavior beavior = new ServiceMetadataBehavior();
                    beavior.HttpGetEnabled = true;
                    beavior.HttpGetUrl = new Uri("http://127.0.0.1:8888/calculatorservice/metadata");
                    host.Description.Behaviors.Add(beavior);

                }
                host.Opened += delegate
                {
                    Console.WriteLine("该服务已经启动,按任意按钮停止");
                };
                host.Open();
                Console.Read();
            }

调用实例:

 

备注:在启动的服务的时候 [Windows7系统中] 要以管理员的身分启动。不然程序会抛出异常信息。。

posted @ 2013-03-20 22:51  在 水 一 方  阅读(315)  评论(0编辑  收藏  举报