2

I register ActionFilterAttribute in ConfigureServices, but I want to inject the service in CustomActionFilter by KeyFilter attribute

public class CustomActionFilter : ActionFilterAttribute
{
    public CustomActionFilter([KeyFilter("test2")]IService service)
    {
    }
} 

Filter Registration:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddScoped<CustomActionFilter>();
}

public class Service1 : IService
{

}

public class Service2 : IService
{

}

builder.RegisterType<Service1>().Keyed<IService>("test1");
builder.RegisterType<Service2>().Keyed<IService>("test2");

Is anyone has idea, how can I register filter to support key filtering?

Peyman
  • 2,920
  • 1
  • 15
  • 29

1 Answers1

0

You need to make sure that IService and any other dependencies of the action filter are registered as well.

public IServiceProvider ConfigureServices(IServiceCollection services) {
    //...

    // Autofac
    services.AddAutofac();

    var builder = new ContainerBuilder();

    //core integration
    builder.Populate(services);

    // Register the components getting filtered with keys
    builder.RegisterType<Service1>().Keyed<IService>("test1");
    builder.RegisterType<Service2>().Keyed<IService>("test2");

    // Attach the filtering behavior to the component with the constructor
    builder.RegisterType<CustomActionFilter>().WithAttributeFiltering();

    var container = builder.Build();    
    var serviceProvider = new AutofacServiceProvider(container);

    return serviceProvider;
}

Custom filters are added to the controller method and the controller class using the ServiceFilter attribute like so:

[ServiceFilter(typeof(CustomActionFilter))]
[Route("api/custom")]
public class CustomController : Controller {
    // GET: api/issues
    [HttpGet]
    [ServiceFilter(typeof(CustomActionFilter))]
    public IActionResult Get() { 
        //...
    }
}

Or you could have registered it globally in ConfigureServices like

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc(options => {
        options.Filters.Add(typeof(CustomActionFilter)); // by type        
    });

    //...
}

Reference Filters : Dependency injection

Reference AutoFac : KeyFilterAttribute Class

Nkosi
  • 191,971
  • 29
  • 311
  • 378
  • Thanks for the answer, but it's not what Im looking for. As you see in my sample code, I want to filter IService by key. I have 2 implementation of IService and want to filter them by key – Peyman Jan 15 '18 at 03:23
  • you mean by default support KeyFilter? – Peyman Jan 15 '18 at 03:31
  • @Peyman look at the comments in the code. Came from documentation which was also linked at the end of the post. – Nkosi Jan 15 '18 at 03:34
  • Thanks @Nkosi, just missed first line services.AddAutofac(); – Peyman Jan 15 '18 at 03:43