托管(3)
[ServiceContract] interface IMyContract {...} class MyService : IMyContract {...} 我们可以编写如下的托管代码: public static void Main() { Uri baseAddress = new Uri(http://localhost:8000
|
[ServiceContract] interface IMyContract {...} class MyService : IMyContract {...} 我们可以编写如下的托管代码: public static void Main() { Uri baseAddress = new Uri("http://localhost:8000/"); ServiceHost host = new ServiceHost(typeof(MyService),baseAddress); host.Open(); //可以执行用于阻塞的调用: Application.Run(new MyForm()); host.Close(); }
|
打开宿主时,将装载WCF运行时(WCF runtime),启动工作线程监控传入的请求。由于引入了工作线程,因此可以在打开宿主之后执行阻塞(blocking)操作。通过显式控制宿主的打开与关闭,提供了IIS托管难以实现的特征,即能够创建定制的应用程序控制模块,管理者可以随意地打开和关闭宿主,而不用每次停止宿主的运行。
使用Visual Studio 2005
Visual Studio 2005允许开发者为任意的应用程序项目添加WCF服务,方法是在Add New Item对话框中选择WCF Service选项。当然,这种方式添加的服务,对于宿主进程而言属于进程内托管方式,但进程外的客户端仍然可以访问它。
自托管与基地址
启动服务宿主时,无需提供任何基地址:
public static void Main() ServiceHost host = new ServiceHost(typeof(MyService)); host.Open(); Application.Run(new MyForm()); host.Close(); }
|
警告:但是我们不能向空列表传递null值,这会导致抛出异常:
serviceHost host; host = new ServiceHost(typeof(MyService),null);
|
只要这些地址没有使用相同的传输样式(Transport Schema),我们也可以注册多个基地址,并以逗号作为地址之间的分隔符。代码实现如下所示(注意例1-3中params限定符的使用):
Uri tcpBaseAddress = new Uri("net.tcp://localhost:8001/"); Uri httpBaseAddress = new Uri("http://localhost:8002/"); ServiceHost host = new ServiceHost(typeof(MyService), tcpBaseAddress,httpBaseAddress);
|
|