Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a Global Action Filter to all Controllers in an Area using MVC 3 Dependency Injection with Ninject 2.2

I was able to to use ASP.NET MVC 3 and Ninject 2.2 to inject a logger object into a custom ActionFilterAttribute thanks to the help I received in this post.

Now I would like to bind my custom ActionFilterAttribute only to all controllers that are in a specific area.

I was able to get started with the following binding but it only handles one controller in a certain area. I would like my code to bind to all controllers in a specific area. Any ideas?

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ILogger>().To<Log4NetLogger>().InRequestScope();
    kernel.BindFilter<TestLoggingAttribute>(
        FilterScope.Controller, 0)
            .WhenControllerType<OrganizationController>();
}
like image 422
Ken Burkhardt Avatar asked Dec 22 '22 16:12

Ken Burkhardt


2 Answers

This helped me, Thanks Darin. However, context.RouteData.Values did not have the area for me but context.RouteData.DataTokens["area"] did! also in my case I had controller that were not in specific areas (e.g. shared controllers) therefore I had to check for datatoken area to be null. This is what worked for me:

kernel
   .BindFilter<TestLoggingAttribute>(FilterScope.Controller, 0)
   .When((context, ad) => context.RouteData.DataTokens["area"] != null && context.RouteData.DataTokens["area"] == "Organization");
like image 128
EdwinG Avatar answered Dec 29 '22 12:12

EdwinG


kernel
    .BindFilter<TestLoggingAttribute>(FilterScope.Controller, 0)
    .When((context, ad) => context.RouteData.Values["area"] == "YourAreaName");

or:

kernel
    .BindFilter<TestLoggingAttribute>(FilterScope.Controller, 0)
    .When((context, ad) => context.Controller.GetType().FullName.Contains("Areas.YourAreaName"));
like image 33
Darin Dimitrov Avatar answered Dec 29 '22 10:12

Darin Dimitrov