编程实现WCF服务

时间:2022-07-31 19:05:13

首先当然是编写契约啦,为了实现契约代码的复用,这里单独将契约写在一个类库里面Wcf.Contract

 1 using System;
 2 using System.ServiceModel;
 3 
 4 namespace Wcf.Contract
 5 {
 6     [ServiceContract(Name="operation",Namespace="urlns://little.org")]
 7     public interface IOperation
 8     {
 9         Guid InstanceId{ get; }
10         [OperationContract]
11         int Add(int a,int b);
12         [OperationContract]
13         int Sub(int a,int b);
14         [OperationContract]
15         int Muti(int a,int b);
16         [OperationContract]
17         int Devide(int a,int b);
18     }
19 }

然后就是服务实现啦,将服务实现单独写在一个类库里面 新建一个类库项目Wcf.Service,并添加Wcf.Contract 引用

using System;
using Wcf.Contract;

namespace Wcf.Service
{
    public class Operation:IOperation
    {
        public Guid InstanceId
        {
            get
            {
                return Guid.NewGuid();
            }
        }

        public int Add(int a,int b)
        {
            return a + b;
        }

        public int Sub(int a,int b)
        {
            return a - b;
        }

        public int Muti(int a,int b)
        {
            return a * b;
        }

        public int Devide(int a,int b)
        {
            return a / b;
        }
    }
}

然后就是服务的承载了,我们新建一个Wcf.Host 的控制台项目,在控制台中承载服务

 1 using System;
 2 using System.ServiceModel;
 3 using Wcf.Service;
 4 
 5 namespace Wcf.Host
 6 {
 7     class MainClass
 8     {
 9         public static void Main (string[] args)
10         {
11             Uri[] baseAddresses = new Uri[] {
12                 new Uri ("http://localhost:8081/operation", UriKind.Absolute)
13             };
14             ServiceHost host = new ServiceHost (typeof(Wcf.Service.Operation), baseAddresses);
15 
16             host.AddServiceEndpoint ("Wcf.Contract.IOperation", new BasicHttpBinding (), "");
17             host.Opened += OnServiceHostOpened;
18             try
19             {
20                 host.Open();
21             }
22             catch(Exception ex) {
23                 //Console.BackgroundColor = ConsoleColor.Red;
24                 Console.WriteLine (ex.Message);
25                 //Console.ResetColor ();
26             }
27             Console.WriteLine ("press any key to exit...");
28             Console.ReadKey ();
29 
30 
31         }
32 
33         public static void OnServiceHostOpened(object sender,EventArgs e)
34         {
35             Console.WriteLine ("ServiceHost has opened.");
36         }
37     }
38 }

这样就简单实现了一个Wcf服务,没有使用配置文件