使用Autofac KeyFilterAttibute将服务注入Action Filter

时间:2018-01-15 01:04:11

标签: c# asp.net-core autofac

我在ActionFilterAttribute注册了ConfigureServices,但我希望通过CustomActionFilter属性

KeyFilter中注入服务
public class CustomActionFilter : ActionFilterAttribute
{
    public CustomActionFilter([KeyFilter("test2")]IService service)
    {
    }
} 

过滤器注册:

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");

有人有想法,我如何注册过滤器以支持密钥过滤?

1 个答案:

答案 0 :(得分:0)

您需要确保同时注册了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; } 和操作过滤器的任何其他依赖项。

ServiceFilter

自定义过滤器使用[ServiceFilter(typeof(CustomActionFilter))] [Route("api/custom")] public class CustomController : Controller { // GET: api/issues [HttpGet] [ServiceFilter(typeof(CustomActionFilter))] public IActionResult Get() { //... } } 属性添加到控制器方法和控制器类中,如下所示:

ConfigureServices

或者您可以在public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(typeof(CustomActionFilter)); // by type }); //... } 中全球注册

(x + y * self.width) / 8

参考Filters : Dependency injection

参考AutoFac : KeyFilterAttribute Class