6: foreach (ServiceTypeElement element in settings.ServiceTypes)
7: {
8: this.Add(element.ServiceType);
9: }
10:
11: if (null != serviceTypes)
12: {
13: Array.ForEach(serviceTypes, serviceType=> this.Add(new ServiceHost(serviceType)));
14: }
15: }
16: public void Add(params Type[] serviceTypes)
17: {
18: if (null != serviceTypes)
19: {
20: Array.ForEach(serviceTypes, serviceType => this.Add(new ServiceHost(serviceType)));
21: }
22: }
23: public void Open()
24: {
25: foreach (ServiceHost host in this)
26: {
27: host.Open();
28: }
29: }
30: public void Dispose()
31: {
32: foreach (IDisposable host in this)
33: {
34: host.Dispose();
35: }
36: }
37: }
定义在ServiceHostCollection中的Open方法实现了对所有ServiceHost对象的批量开启。ServiceHostCollection还实现了IDisposable接口,并在Dispose方法中实现了对ServiceHost的批量关闭。
现在我们定义了FooService、BarService和BazService三个服务类型,它们分别实现了契约接口IFoo、IBar和IBar。三个服务以及包含的终结点定义在如下的配置中,而三个服务类型同时被定义在了我们自定义的配置节下。
1:
2:
3:
4: type="Artech.BatchingHosting.Configuration.BatchingHostingSettings,
5: Artech.BatchingHosting"/>
6:
7:
8:
9:
10:
11: binding="ws2007HttpBinding"
12: contract="Artech.BatchingHosting.IFoo"/>
13:
14:
15:
16: binding="ws2007HttpBinding"
17: contract="Artech.BatchingHosting.IBar"/>
18:
19:
20:
21: binding="ws2007HttpBinding"
22: contract="Artech.BatchingHosting.IBaz"/>
23:
24:
25:
26:
27:
28:
29:
30:
31:
要实现针对三个服务的批量寄宿,我们只需要创建ServiceHostCollection对象并开启它即可。为了确认三个服务对应的ServiceHost确实被创建并被开启,我通过如下的代码注册了ServiceHostCollection中每个ServiceHost的Opened事件。当该事件触发时,会在控制台上打印一段文字。
1: using (ServiceHostCollection hosts = new ServiceHostCollection())
2: {
3: foreach (ServiceHost host in hosts)
4: {
5: host.Opened += (sender, arg) => Console.WriteLine("服务{0}开始监听",
6: (sender as ServiceHost).Description.ServiceType);
7: }
8: hosts.Open();
9: Console.Read();
10: }
上面这段代码执行之后,控制台上将会具有如下一段输出文字,这充分证明了我们对三个服务成功地进行了批量寄宿。
1: 服务Artech.BatchingHosting.FooService开始监听
2: 服务Artech.BatchingHosting.BarService开始监听
3: 服务Artech.BatchingHosting.BazService开始监听