log4net、Castle Windsor和Global.asax中的Application_Error方法
本文关键字:Application 中的 Error 方法 asax Global Castle Windsor log4net | 更新日期: 2023-09-27 18:19:09
我按照教程使用Windsor容器设置log4net。与教程一样,我设置了LoggerInstaller类:
public class LoggerInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<LoggingFacility>(
f => f.LogUsing(LoggerImplementation.Log4net)
.WithConfig("log4net.config"));
}
}
在全局。因此,我有以下方法:
private static void BootStrapContainer()
{
container = new WindsorContainer()
.Install(FromAssembly.This());
var controllerFactory = new WindsorControllerFactory(container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
BootStrapContainer();
}
和要注入的ILogger类型:
public ILogger Logger { get; set; }
这在具有ILogger属性的控制器上工作得很好,但我似乎无法让它注入Global.asax。我想做的是在Application_Error方法中记录未处理的异常,如下所示:
void Application_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
Logger.Error("App_Error", ex);
}
LoggerInstaller在Application_Start()期间被调用,但没有注入。任何帮助都会很感激。我想可能是我忽略了一些简单的东西。
"Logger"不会被注入"global "。因为这个类还没有通过Windsor/IoC容器创建(这是不可能的)。
如果你需要logger在"Application_Error"我可能会建议你创建你的容器在"Application_Start",保持它的私有到"global "。类,并在"Application_Error"方法中使用Resolve/Release方法
void Application_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
var logger = _container.Resolve<ILogger>();
logger.Error("App_Error", ex);
_container.Release(logger);
}