wcf services host in a console application

一个serviceHost多个wcf服务,宿主为console

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.ServiceModel;
 5 using System.ServiceModel.Activation;
 6 using System.ServiceModel.Web;
 7 using System.Text;
 8 
 9 namespace WcfRestServiceLibrary.Service
10 {
11     [ServiceContract(Namespace = "WcfRestServiceLibrary.Service")]
12     public interface IMicroblogService
13     {
14         [OperationContract]
15         [WebGet(UriTemplate = "")]
16          List<Microblog> GetCollection();
17 
18         [OperationContract]
19         [WebInvoke(UriTemplate = "", Method = "POST", RequestFormat = WebMessageFormat.Json)]
20         Microblog Create(Microblog microblog);
21 
22         [OperationContract]
23         [WebGet(UriTemplate = "{id}",RequestFormat = WebMessageFormat.Xml,ResponseFormat=WebMessageFormat.Json)]
24         Microblog Get(string id);
25 
26         [OperationContract]
27         [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
28         void Delete(string id);
29 
30         [OperationContract]
31         [WebInvoke(Method = "PUT")]
32         void Modify( Microblog microblog);
33     }
34 }
 1 using System;
 2 using System.Runtime.Serialization;
 3 
 4 namespace WcfRestServiceLibrary.Service
 5 {
 6     [DataContract(Namespace = "WcfRestServiceLibrary.Service")]
 7     public class Microblog
 8     {
 9         [DataMember]
10         public int Id { get; set; }
11         [DataMember]
12         public string Content { get; set; }
13         [DataMember]
14         public DateTime PublishTime { get; set; }
15     }
16 
17 
18 }
 1 using System;
 2 using System.Collections.Concurrent;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Net;
 6 using System.ServiceModel;
 7 using System.ServiceModel.Activation;
 8 using System.ServiceModel.Web;
 9 using System.Threading;
10 
11 namespace WcfRestServiceLibrary.Service
12 {
13     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
14     [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
15     public class MicroblogService:IMicroblogService 
16     {
17         private static int _currentId;
18         private static IList<Microblog> _microblogs = new List<Microblog> 
19         {
20             new Microblog() {Id=5,Content="Hello,haha",PublishTime =DateTime .Now},
21             new Microblog() {Id=6,Content="test,test",PublishTime =Convert.ToDateTime("2014/03/25")}
22         };
23 
24         public List<Microblog> GetCollection()
25         {
26             return _microblogs.ToList();
27         }
28 
29         public Microblog Create(Microblog microblog)
30         {
31             microblog.Id = Interlocked.Increment(ref _currentId);
32             _microblogs.Add(microblog);
33             return microblog;
34         }
35 
36         public Microblog Get(string id)
37         {
38             Microblog microblog = _microblogs.FirstOrDefault(e => e.Id == int.Parse(id));
39             if(null==microblog)
40             {
41                 WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
42             }
43             return microblog;
44         }
45 
46         public void Delete(string id)
47         {
48             Microblog microblog = Get(id);
49             if(null!=microblog)
50             {
51                 _microblogs.Remove(microblog);
52             }
53             
54         }
55 
56         public void Modify(Microblog microblog)
57         {
58             Delete(microblog.Id.ToString());
59             _microblogs.Add(microblog);
60         }
61 
62     }
63 }
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Runtime.Serialization;
 6 using System.ServiceModel.Web;
 7 using System.ServiceModel;
 8 
 9 namespace Artech.WcfServices.Service
10 {
11     [ServiceContract]
12     public interface IEmployees
13     {
14         [WebGet(UriTemplate = "all")]
15         IEnumerable<Employee> GetAll();
16 
17         [WebGet(UriTemplate = "{id}")]
18         Employee Get(string id);
19 
20         [WebInvoke(UriTemplate = "/", Method = "POST")]
21         void Create(Employee employee);
22 
23         [WebInvoke(UriTemplate = "/", Method = "PUT")]
24         void Update(Employee employee);
25 
26         [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
27         void Delete(string id);
28     }
29 
30     [DataContract(Namespace = "Artech.WcfServices.Service")]
31     public class Employee
32     {
33         [DataMember]
34         public string Id { get; set; }
35         [DataMember]
36         public string Name { get; set; }
37         [DataMember]
38         public string Department { get; set; }
39         [DataMember]
40         public string Grade { get; set; }
41 
42         public override string ToString()
43         {
44             return string.Format("ID: {0,-5}姓名: {1, -5}级别: {2, -4} 部门: {3}", Id, Name, Grade, Department);
45         }
46     }
47 }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Web;
using System.Net;

namespace Artech.WcfServices.Service
{
public class EmployeesService : IEmployees
{
    private static IList<Employee> employees = new List<Employee>
    {
        new Employee{ Id = "001", Name="张三", Department="开发部", Grade = "G7"},    
        new Employee{ Id = "002", Name="李四", Department="人事部", Grade = "G6"}
    };
    public Employee Get(string id)
    {
        Employee employee = employees.FirstOrDefault(e => e.Id == id);
        if (null == employee)
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
        }
        return employee;
    }
    public void Create(Employee employee)
    {
        employees.Add(employee);
    }
    public void Update(Employee employee)
    {
        this.Delete(employee.Id);
        employees.Add(employee);
    }
    public void Delete(string id)
    {
        Employee employee = this.Get(id);
        if (null != employee)
        {
            employees.Remove(employee);
        }
    }
    public IEnumerable<Employee> GetAll()
    {
        return employees;
    }
}
}

以下是控制台程序,wcf宿主在console:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Configuration;
 4 using System.Linq;
 5 using System.Reflection;
 6 using System.ServiceModel;
 7 using System.ServiceModel.Configuration;
 8 
 9 namespace ConsoleApplication1
10 {
11     class Program
12     {
13         static List<ServiceHost> listHost = null;
14         static ServiceHost host = null;
15         static void Main(string[] args)
16         {
17             //Uri baseAddress = new Uri("http://localhost:8083/MicroblogService");
18             //ServiceHost _host = new ServiceHost(typeof(MicroblogService), baseAddress);
19             
20             ////WebServiceHost _host = new WebServiceHost(typeof(MicroblogService),baseAddress);
21             //using (_host)
22             //{
23             //    ServiceEndpoint endPoint = _host.AddServiceEndpoint(typeof(IMicroblogService), new WebHttpBinding(), baseAddress);
24             //    WebHttpBehavior httpBehavior = new WebHttpBehavior();
25             //    httpBehavior.HelpEnabled = true;
26             //    endPoint.Behaviors.Add(httpBehavior);
27             //    _host.Opened += delegate
28             //    {
29             //        Console.WriteLine("Console Hosted successfully.");
30             //    };
31             //    _host.Open();
32             //    Console.ReadLine();
33             //}
34             //WebServiceHost _host = new WebServiceHost(typeof(MicroblogService));
35             //_host.Opened += delegate
36             //{
37             //    Console.WriteLine("Console Hosted successfully.");
38             //};
39             //_host.Open();
40             //Console.ReadLine();
41 
42             OpenService();
43             Console.ReadLine();
44         }
45 
46         public static void OpenService()
47         {
48             try
49             {
50                 listHost = new List<ServiceHost>();
51                 Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
52 
53                 if (conf != null)
54                 {
55                     ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");
56                     foreach (ServiceElement el in svcmod.Services.Services)
57                     {
58 
59                         string klassName = el.Name.Substring(el.Name.LastIndexOf(.) + 1);
60                         Assembly asmb = Assembly.LoadFrom(klassName + ".dll");
61                         Type svcType = asmb.GetType(el.Name);
62 
63                         if (svcType == null)
64                         {
65                             continue;
66                         }
67                         host = new ServiceHost(svcType);
68 
69                         host.Open();
70                         if (!listHost.Contains(host))
71                         {
72                             listHost.Add(host);
73                         }
74                     }
75                 }
76             }
77             catch (Exception ex)
78             {
79                 Console.WriteLine(ex.Message );
80             }
81         }
82     }
83 }

app.config:

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <configuration>
 3   <system.serviceModel>
 4     <services>
 5       <!-- This section is optional with the new configuration model
 6            introduced in .NET Framework 4. -->
 7       <service name="WcfRestServiceLibrary.Service.MicroblogService" behaviorConfiguration="MicroblogServiceBehavior">
 8         <host>
 9           <baseAddresses>
10             <add baseAddress="http://127.0.0.1:8034/MicroblogService"/>
11           </baseAddresses>
12         </host>
13         <endpoint address="http://127.0.0.1:8034/MicroblogService"
14                   binding="webHttpBinding"
15                   contract="WcfRestServiceLibrary.Service.IMicroblogService"  behaviorConfiguration="web"/>
16       </service>
17 
18       <service name="Artech.WcfServices.Service.EmployeesService" behaviorConfiguration="EmployeesServiceBehavior">
19         <host>
20           <baseAddresses>
21             <add baseAddress="http://127.0.0.1:3724/EmployeesService"/>
22           </baseAddresses>
23         </host>
24         <endpoint address="http://127.0.0.1:3724/EmployeesService"
25                   binding="webHttpBinding"
26                   contract="Artech.WcfServices.Service.IEmployees" behaviorConfiguration="web"/>
27       </service>
28 
29     </services>
30 
31     <behaviors>
32       <serviceBehaviors>
33         <behavior name="MicroblogServiceBehavior" >
34           <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:8034/MicroblogService/MetaData"/>
35         </behavior>
36         <behavior name="EmployeesServiceBehavior" >
37           <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:3724/EmployeesService/MetaData"/>
38         </behavior>
39       </serviceBehaviors>
40       <endpointBehaviors>
41         <behavior name="web">
42           <webHttp helpEnabled="true" />
43         </behavior>
44       </endpointBehaviors>
45     </behaviors>
46 
47     <!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />-->
48   </system.serviceModel>
49 </configuration>

启动console程序,运行测试:

以上足以证明,控制台程序一启动,两个wcf service都可正常使用了。

wcf services host in a console application,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。