c# - 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<>));
}
}
解决方案
您可以将类型作为参数存储在操作过滤器中。
[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()
{
}
推荐阅读
- html - 如何围绕另一个组织元素?
- removeeventlistener - 添加/删除事件监听器 -
- python - 如何设置从第三列绘制值的条件?蟒蛇/熊猫
- java - 尝试连接 JSON 服务器时出现异常
- c# - 需要一个用于字母数字小写和 . 和 _
- xaml - 如何从 C++/CX 中的 XAML 资源中获取 CommandBar?
- python - 在 Pandas 中设置 Gmaps 边界
- php - Ajax:尝试使用相对路径时出现发布错误
- node.js - node.js 中的 MVC 对开发 restful api 很重要吗?
- vue.js - Vuetify 图标显示在轮播上,但不在 v-icon 上