You can use your own extension for the ContainerBuilder class for the Autofac library:
public static class ContainerBuilderExtensions { public static void RegisterWebApiFilterAttribute<TAttribute>(this ContainerBuilder builder, Assembly assembly) where TAttribute : Attribute, IAutofacAuthorizationFilter { Type[] controllerTypes = assembly.GetLoadableTypes() .Where(type => typeof(ApiController).IsAssignableFrom(type)).ToArray(); RegisterFilterForControllers<TAttribute>(builder, controllerTypes); RegisterFilterForActions<TAttribute>(builder, controllerTypes); }
Then you can make one registration for the entire assembly, and not for each controller:
public class LoggerFilterAttribute : Attribute, IAutofacAuthorizationFilter { private readonly ILog _logger;
Registration:
builder.RegisterWebApiFilterAttribute<LoggerFilterAttribute>(Assembly.GetExecutingAssembly());
You can use your attribute on a controller or action:
public class AuthorsController : ApiController {
The whole demo project is on github
source share