【问题标题】:Inject service into Action Filter with Autofac KeyFilterAttibute使用 Autofac KeyFilterAttibute 将服务注入操作过滤器
【发布时间】:2018-06-23 15:46:19
【问题描述】:

我在ConfigureServices中注册了ActionFilterAttribute,但我想通过KeyFilter属性在CustomActionFilter中注入服务

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

有人知道吗,如何注册过滤器以支持密钥过滤?

【问题讨论】:

标签: c# asp.net-core autofac


【解决方案1】:

您需要确保IService 和操作过滤器的任何其他依赖项也已注册。

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

    //...
}

参考Filters : Dependency injection

参考AutoFac : KeyFilterAttribute Class

【讨论】:

  • 感谢您的回答,但这不是我要找的。正如您在我的示例代码中看到的,我想按键过滤 IService。我有 2 个 IService 实现,并希望按键过滤它们
  • 你的意思是默认支持KeyFilter?
  • @Peyman 查看代码中的 cmets。来自文章末尾也链接的文档。
  • 谢谢@Nkosi,刚刚错过了一线服务。AddAutofac();
猜你喜欢
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多