Am using Castle windsor 3.0 in my Wcf services project. I'm hosting it as windows service project using Topshelf. All my wcf services configuration is on app.config file. I'm using castle wcffacility and registering services like this -
Container.AddFacility<WcfFacility>();
Container.AddFacility<LoggingFacility>(f => f.UseLog4Net());
container.Register(
Classes
.FromThisAssembly()
.Pick()
.If(x => x.IsClass
&& HasServiceContract(x))
.WithServiceDefaultInterfaces()
.Configure(c => c.AsWcfService().LifeStyle.HybridPerWcfOperationTransient()));
This injects ILog (from log4net) into my services without any problem but it fails to inject into IErrorHandler.
I have added ServiceBehaviour with IErrorHandler so that I can catch user unhandled exceptions and log the errors using the below code.
#region IErrorHandler Members
public ILog Logger { get; set; }
public bool HandleError(Exception error)
{
if (error is FaultException)
return false; // Let WCF do normal processing
return true; // Fault message is already generated
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
var uniqueKey = UniqueKeyGenerator.Generate();
//create the custom wcfexception before passing that to client
var wcfException = new CustomServerException("Unknown Error has occured. Please contact your administrator!", uniqueKey);
//log the exception
Logger.Error(uniqueKey, error);
MessageFault messageFault = MessageFault.CreateFault(
new FaultCode("Sender"),
new FaultReason(wcfException.Message),
wcfException,
new NetDataContractSerializer());
fault = Message.CreateMessage(version, messageFault, null);
}
I looked at this stackoverflow post but it was too old and no answer was posted so am posting this new question.
Update
I got this resolved (partially for now) with the answer provided by greyAlien. All I had to do was
register custom servicebehavior class to castle windsor.
Container.Register( Component.For<IServiceBehavior>() .ImplementedBy<PassThroughExceptionHandlingBehaviour>() .Named("IServiceBehavior")
Remove the serviceBehaviour extension from the app.config file. When I add behavior extension in config file, for some reason, castle is not able to inject the dependencies instead I think Wcf is creating new instances and logger public property is turning out to be null.
It works for me now but need to understand (in future) on how to inject dependencies using behaviourextensions as well.