I have an ASP.NET MVC application for which I want to log events. I have already a Log class with all the tools I need, but I have to instantiate and to close it explicitly
you can use modules because they both sit in a pipeline and can provide pre and post processing for the core execution of a request. BeginRequest / ActionExecuting and EndRequest / ResultExecuted. They both also provide authorization hooks.
http://msdn.microsoft.com/en-us/library/aa719858(v=vs.71).aspx
If the other suggestions don't work or if you need to do things other than just logging also be aware that you can override the OnActionExecuting method (often in a base class for reuse).
// Custom controller.
public class CustomController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Do whatever here...
}
}
// Home controller.
public class HomeController : CustomController
{
// Action methods here...
}
I would recommend you to push in a Logger (probably ILogger) object as a dependency to your controller. You can control the lifetime of this logger object by a DI container (Unity, for example) - and if neccessary you can define its lifetime as request scoped. The other benefit of this soution that your code will remain testable.