Service Host:
using System; using System.Configuration; using System.ServiceModel; using System.ServiceModel.Activation; using System.Web.Configuration; using log4net; using System.Threading; namespace Test.Custom { public class CustomServiceHostFactory : System.ServiceModel.Activation.WebServiceHostFactory { private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { log4net.Config.XmlConfigurator.Configure(); CustomServiceHost customServiceHost = new CustomServiceHost (serviceType, baseAddresses); log.Info("Create Service Host called"); customServiceHost.incomingServiceType = serviceType; customServiceHost.incomingBaseAddresses = baseAddresses; customServiceHost.Faulted += customServiceHost.OnServiceHostFaulted; return customServiceHost; } } public class CustomServiceHost : ServiceHost { public Type incomingServiceType { get; set; } public Uri[] incomingBaseAddresses { get; set; } private int Attempts = 0; private bool isSuccess = false; private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public CustomServiceHost (Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses) { log.Info("CustomServiceHost constructor called"); } protected override void ApplyConfiguration() { base.ApplyConfiguration(); } public void OnServiceHostFaulted(object sender, EventArgs e) { log.Info("Host state is fault."); ICommunicationObject faultedHost = (ICommunicationObject)sender; faultedHost.Abort(); faultedHost = new ServiceHost(this.incomingServiceType, this.incomingBaseAddresses); //faultedHost.Faulted += this.OnServiceHostFaulted; log.Info("Host state is " + faultedHost.State.ToString()); if (Attempts < 5 && isSuccess == false) { Attempts++; log.Info("Retry to create server host for the" + Attempts + "time"); try { if (isSuccess == false) { Thread.Sleep(1 * 1000); } faultedHost.Open(); isSuccess = true; } catch (Exception ex) { faultedHost.Abort(); log.Info("Host state is " + faultedHost.State.ToString()); log.Info("Exception: " + ex.Message); } } } //protected override void OnFaulted() //{ // base.OnFaulted(); //} } }