How does Ninject and MVC resolve this custom attribute to the custom action filter?

585 views Asked by At

I actually have the following code working, but I really am not sure how MVC or Ninject is actually able to bind the LogFilter to the ILoggerMVCAttribute. I guess at some level it makes sense that a filter would have attributes, but I just am not seeing what commonality (interface or base class) allows this to happen. Just trying to gain a better understanding, in case I need to do something like this again in the future. Thanks in advance.

//Basic trimmed down code
//Custom Action Filter
public class LogFilter : System.Web.Mvc.IActionFilter
{
    public class ILogger logger {get;set;}

    public LogFilter(ILogger logger)
    {
        this.logger = logger;
    }

    public void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext)
    {
        LogRequest(logger);
    }

    public void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
    {

    }

}
//Custom Action Filter Attribute
public class ILoggerMVCAttribute : FilterAttribute { }

//Ninject binding the action filter to the action filter attribute.
this.BindFilter<LogFilter>(System.Web.Mvc.FilterScope.Controller, 0)
            .WhenControllerHas<ILoggerMVCAttribute>();

For the record, I did not end up using the above approach for my logging. I was able to get the current instance of my logger in the Global.asax LogRequest as follows.

protected void Application_LogRequest(Object sender, EventArgs e)
{
    ILogger log = this.Kernel.Get<ILogger>();        
    LogRequest(log);
}
1

There are 1 answers

1
Remo Gloor On BEST ANSWER