Thursday, 22 August 2013

Castle Windsor not supplying NLog component when using ASP.NET MVC filters

Castle Windsor not supplying NLog component when using ASP.NET MVC filters

Registration
container.AddFacility<LoggingFacility>(f =>
f.LogUsing(LoggerImplementation.NLog)
.WithConfig("NLog.config"));
This code is as per this documentation page.
Now this is the code where NLog will be used i.e. Castle Windsor will
supply NLog as the _logger implementation:
public class EmailController : Controller
{
private ILogger _logger = NullLogger.Instance;
...
public ILogger Logger
{
get { return _logger; }
set { _logger = value; }
}
public ActionResult Send(UserMessageModel userMessage, bool
captchaValid, string captchaErrorMessage)
{
if (ModelState.IsValid)
{
try
{
// Do something
}
catch (Exception ex)
{
_logger.Error(string.Format("Error msg:{0}\rError
stacktrace:{1}", ex.Message, ex.StackTrace));
...
}
}
...
}
}
However if I change the code thus:
[CustomHandleError] public class EmailController : Controller {
[CustomHandleError] public ActionResult Send(UserMessageModel userMessage,
bool captchaValid, string captchaErrorMessage) {
if (ModelState.IsValid)
{
// Do something
}
...
}
...
}
public class CustomHandleError: HandleErrorAttribute
{
private ILogger _logger = NullLogger.Instance;
public ILogger Logger
{
get { return _logger; }
set { _logger = value; }
}
public override void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
base.OnException(null);
}
_logger.Error(string.Format("Error msg:{0}\rError stacktrace:{1}",
filterContext.Exception.Message,
filterContext.Exception.StackTrace));
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}
}
}
In this case the _logger is "NullLogger.Instance". I thought that the fact
that I had a "Logger" property meant that Castle Windsor would then change
_logger to NLog similar to the previous code.
What could I be misunderstanding?

No comments:

Post a Comment