我正在尝试在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<>));
}
}
答案 0 :(得分:-1)
您可以将操作过滤器中的类型存储为参数。
[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()
{
}