我有一些一次性初始化任务要在服务启动时完成,为了做到这一点,我定义了一个自定义的 ServiceHostFactory 和 ServiceHost 来覆盖 InitializeRuntime。
Service1.svc 标记:
<%@ ServiceHost Language="C#" Debug="true" Factory="service.Our_Service_Host_Factory" Service="service.Service1" CodeBehind="Service1.svc.cs" %>
服务主机定义:
public class Our_Service_Host_Factory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
return new Our_Service_Host(serviceType, baseAddresses);
}
}
class Our_Service_Host : ServiceHost
{
public Our_Service_Host(Type serviceType, Uri[] baseAddresses)
: base(serviceType, baseAddresses) { }
protected override void InitializeRuntime()
{
// one time setup code
}
}
来自 web.config 的片段:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
如果我删除 ServiceHost 标记上的 Factory 属性,WCF 测试客户端可以成功连接到我的服务。如果我把它放回去,它找不到元数据端点并出现以下错误:
Error: Cannot obtain Metadata from http://localhost:50154/Service1.svc If this is a Windows (R)
Communication Foundation service to which you have access, please check that you have enabled
metadata publishing at the specified address. For help enabling metadata publishing, please
refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata
Exchange Error URI: http://localhost:50154/Service1.svc Metadata contains a reference that
cannot be resolved: 'http://localhost:50154/Service1.svc'. There was no endpoint listening at
http://localhost:50154/Service1.svc that could accept the message. This is often caused by an
incorrect address or SOAP action. See InnerException, if present, for more details. The
remote server returned an error: (404) Not Found.HTTP GET Error URI:
http://localhost:50154/Service1.svc There was an error
downloading 'http://localhost:50154/Service1.svc'. The request failed with HTTP status 404:
Not Found.
看起来有一个自定义的 ServiceHost/ServiceHostFactory 可能会破坏简化的配置。是这种情况,还是有什么我忽略的东西会使它继续起作用?