【引自张逸的博客】WCF宿主与服务托管
若要公开WCF服务,需要提供一个运行服务的宿主环境。就像.NET CLR需要创建宿主环境以托管代码一般,WCF的宿主环境同样运行在进程的应用程序域中。在应用程序域中可以创建一个或多个ServiceHost实例,其关系如图一所示:
 |
| 图1:托管ServiceHost |
WCF并不推荐在应用程序域中创建多个ServiceHost实例。如果要托管多个服务,完全可以在一个宿主中通过多个Endpoint公开多个WCF服务。由于应用程序域对安全进行了隔离,如果需要提供不同的安全上下文,则有必要创建多个ServiceHost实例。
WCF的典型宿主包括以下四种:
1、"Self-Hosting" in a Managed Application(自托管宿主)
2、Managed Windows Services(Windows Services宿主)
3、Internet Information Services(IIS宿主)
4、Windows Process Activation Service(WAS宿主)
以下将通过一个具体的实例分别介绍这几种宿主的托管方式及其相关的注意事项。在这样的一个实例中,我们定义了如下的服务契约:
namespace BruceZhang.WCF.DocumentsExplorerServiceContract { [ServiceContract] public interface IDocumentsExplorerService { [OperationContract] [FaultContract(typeof(DirectoryNotFoundException))] DocumentList FetchDocuments(string homeDir);
[OperationContract] Stream TransferDocument(Document document); } }
|
服务的实现则如下所示:
namespace BruceZhang.WCF.DocumentsExplorerServiceImplementation { [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class DocumentsExplorerService : IDocumentsExplorerService { #region IDocumentsExplorerService Members public DocumentList FetchDocuments(string homeDir) { //implementation code } public Stream TransferDocument(Document document) { //implementation code } #endregion } }
|
在服务契约的操作中,DocumentList与Document则为自己定义的数据契约:
namespace BruceZhang.WCF.DocumentsExplorerDataContract { [DataContract] public class Document { //DataMembers } } namespace BruceZhang.WCF.DocumentsExplorerDataContract { [KnownType(typeof(Document))] [CollectionDataContract] public class DocumentList:IList { //IList Methods } }
|
注意以上定义的服务契约、服务类与数据契约的命名空间。