首页 > 解决方案 > ActionFilterAttribute 内的 aspnet core mvc 访问依赖指示服务

问题描述

我正在尝试访问 ActionFilterAttribute 中的以下服务。

IFooService服务

 public interface IFooService<T>
 {
     List<T> GetFoos { get; set; }
 }

实施 *FooService**

public class FooService : IFooService<int>
{
    public List<int> GetFoos()
    {
       //do something interesting here.
           return new List<int>();
    }
}

上述服务在 aspnetcore 依赖容器中注册为:

services.AddScoped<IFooService<int>, FooService>();

我想在我的属性中使用 IFooService 。但是,在属性级别,我不知道类型参数。

是否可以在不知道类型参数的情况下在 ActionFilterAttribute 中找到上述服务?我希望能够仅在接口上调用 GetFoos 方法。

//这是我的尝试。

 public class FooActionFilter : ActionFilterAttribute
 {
      public override void OnActionExecuted(ActionExecutedContext context)
      {
            //error here generic service require 1 argument. But i don't know how to pass this argument..
            var foo = (IFooService) context.HttpContext.RequestServices.GetService(typeof(IFooService<>));                                    
      }
 }

标签: c#asp.net-coreasp.net-core-mvc

解决方案


您可以将类型作为参数存储在操作过滤器中。

[AttributeUsage(AttributeTargets.Method)]
public class FooActionFilterAttribute : ActionFilterAttribute
{
    public FooActionFilterAttribute(Type serviceType)
    {
        ServiceType = serviceType;
    }

    public Type ServiceType { get; }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        var service =  context.HttpContext.RequestServices.GetService(ServiceType) as FooService;                   
    }
}

// usage
[FooActionFilter(typeof(IFilterService<int>))]
public IActionResult ActionMethod()
{
}

推荐阅读