日期:2014-05-16 浏览次数:21493 次
问题及环境:在web项目中直接添加的wcf服务。web项目中增加Global.asax,在Global.asax的Application_Start事件中注册log4net
  protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
        }
于是,在IIS上浏览svc文件。再调用WCF服务时日志正常。
Application_Start在直接调用的时候并没有被执行,只有在浏览svc页面时才被执行了。
所以在global中注册log4net只能靠运维部署时来浏览svc来启动日志。
怎么解决呢?
使用自定义ServiceHost
默认的IIS宿主只能创建ServiceHost实例 ,所以在自定义的ServiceHost实例中来注册log4net启动日志记录是最好的选择了。
如下,自定义一个ServiceHost的子类
一个ServiceHostFactory的子类
using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace Test
{
    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();
        }
    }
}
在<%@ ServiceHost Language="C#" Debug="true" Service="Test.CustomService" CodeBehind=“Test.CustomService.svc.cs”>中加入
Factory=“Test.CustomServiceHostFactory”
即<%@ ServiceHost Language="C#" Debug="true" Service="Test.CustomService" Factory=“Test.CustomServiceHostFactory” CodeBehind=“Test.CustomService.svc.cs”>
再次部署后,第一次调用IIS上的WCF服务也可以自动启动记录日志了