当前位置:有风信息港IT学院编程技术.net → Host多个WCF服务(Self-host)

Host多个WCF服务(Self-host)

减小字体 增大字体 作者:有风IT学院  来源:有风信息港  发布时间:2008-1-13 9:07:29
如果用self-host的方式来加载服务的话,我们一般是用这样的代码:ServiceHost host1 = new ServiceHost(typeof(UserService)); 问题是,如果当你的服务很多的时候这样做是不胜其烦的,今天在看Ingo Rammer(大名鼎鼎的《Advanced .Net Remoting》作者)的Blog的时候,看到了他解决这一问题的方法:
一.服务配置在app.config或web.config中:



1using System;
2using System.Collections.Generic;
3using System.Reflection;
4using System.Configuration;
5using System.ServiceModel.Configuration;
6using System.ServiceModel;
7
8public class ServiceHostGroup
9{
10 static List _hosts = new List();
11
12 private static void OpenHost(Type t)
13 {
14 ServiceHost hst = new ServiceHost(t);
15 hst.Open();
16 _hosts.Add(hst);
17 }
18
19 public static void StartAllConfiguredServices()
20 {
21 Configuration conf =
22 ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
23
24 ServiceModelSectionGroup svcmod =
25 (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");
26 foreach (ServiceElement el in svcmod.Services.Services)
27 {
28 Type svcType = Type.GetType(el.Name);
29 if (svcType == null)
30 throw new Exception("Invalid Service Type " + el.Name + " in configuration file.");
31 OpenHost(svcType);
32 }
33
34 }
35
36
37 public static void CloseAllServices()
38 {
39 foreach (ServiceHost hst in _hosts)
40 {
41 hst.Close();
42 }
43 }
44}

[1] [2]  下一页