|
我们也可以直接创建一个WCF Service应用程序作为IIS宿主,它会自动创建一个svc文件,如图5所示:
 |
| 图5:创建WCF Service应用程序 | 创建的svc文件如图:
 |
| 图6:创建的svc文件 |
WCF Service应用程序创建的svc文件以及通过添加新项获得svc文件,自动会创建WCF服务。因此,如果我们希望在svc文件中嵌入WCF服务的代码,则可以采取这种方式。例如:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.IO; using BruceZhang.WCF.DocumentsExplorerDataContract; namespace BruceZhang.WCF.DocumentsExplorerServiceImplementation { [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class DocumentsExplorerService : IDocumentsExplorerService { //Service Implementation } }
| 上述代码中的@ServiceHost指示符只能是在右键单击svc文件后,在View Marckup中才能够看到。
Svc文件通过@ServiceHost指示符指定它所要托管的服务,此外还指定了实现服务的语言、调用模式,还可以设置CodeBehind,指定服务代码。不过,在IIS托管中,服务代码或程序集文件受到一定的限制,它只能放在如下的其中一个位置中:
(1)svc文件的内嵌代码中; (2)放在注册于GAC的单独程序集中; (3)驻留于应用程序的Bin文件夹内的程序集中(此时,bin文件夹不必include); (4)驻留于应用程序的App_Code文件夹的源代码文件中(根据Language的设置,或者为C#或者为VB)。
即使我们将服务代码放在应用程序根目录下,或者其它文件夹中,然后通过CodeBehind指定代码的路径,仍然不能托管服务。
如果服务契约与服务类是通过引用的方式在宿主应用程序中,则我们可以直接创建一个扩展名为.svc的单个文件,然后include到应用程序根目录下,如图六中的HostService.svc,该文件没有关联的cs文件。此时,在Visual Studio中直接打开该文件,并不能编写服务代码,而是指定@ServiceHost即可。
注意,上述方式的IIS宿主只能创建ServiceHost实例,如果是自定义的ServiceHost,则需要通过@ServiceHost的Factory来指定创建自定义ServiceHost的工厂类。例如这样的自定义ServiceHost以及相应的工厂类:
using System; using System.ServiceModel; using System.ServiceModel.Activation; namespace BruceZhang.WCF.DocumentsExplorerIISHost { public class CustomServiceHostFactory : ServiceHostFactory { protected override ServiceHost CreateServiceHost( Type serviceType, Uri[] baseAddresses) { CustomServiceHost customServiceHost = new CustomServiceHost(serviceType, baseAddresses); return customServiceHost; } } public class CustomServiceHost : ServiceHost { public CustomServiceHost(Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses) { } protected override void ApplyConfiguration() { base.ApplyConfiguration(); } } }
|
|