我在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");
有人有想法,我如何注册过滤器以支持密钥过滤?
答案 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