c# - 从 DI 容器中注册具有多种类型的通用动作过滤器
问题描述
我正在研究一个Asp.net core 5
有针对性的.net 5
. 我用了Action filter
as generic
。如果任何其他
对象model
在. 如果对象存在或不存在,则泛型类型将替换为要签入的实体名称。Id
Id
TEntity
TEntity
我尝试了什么:
public class ShouldExistFilter<TEntity>:IActionFilter where TEntity : class
{
private readonly AppDbContext _dbContext;
public ShouldExistFilter(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public void OnActionExecuting( ActionExecutingContext context )
{
context.ActionArguments.TryGetValue( "model" , out object model );
var result= _dbContext.Set<TEntity>().Find( model.GetType().GetProperty( "Id" ).GetValue( model ) );
if ( result!=null )
{
// Some logic here
}
}
public void OnActionExecuted( ActionExecutedContext context )
{
}
}
我如何将它与动作一起使用:
第一个例子:
[ServiceFilter(typeof(ShouldExistFilter<SchoolSubject>))]
public async Task<IActionResult> Edit(SchoolSubjectModel model)
{
// Some logic here
}
第二个例子:
[ServiceFilter(typeof(ShouldExistFilter<Student>))]
public async Task<IActionResult> Edit(StudentModel model)
{
// Some logic here
}
问题:
当我尝试注册ShouldExistFilter
inConfigureServices
方法时,我必须将它注册到可能与 the 一起使用的所有实体中,filter
这对我来说不实用,因为我有很多实体。
现在我应该这样做:
services.AddScoped<ShouldExistFilter<SchoolSubject>>();
services.AddScoped<ShouldExistFilter<Student>>();
services.AddScoped<ShouldExistFilter<Absence>>();
...
问题:
如何注册ShouldExistFilter
一次DI Container
并与任何一次一起使用Type
?或者有什么办法可以到达我的对象?
解决方案
除了服务过滤器属性,您还可以使用该[TypeFilter]
属性来创建具有依赖关系的过滤器,而无需向 DI 容器本身注册该过滤器:
[TypeFilter(typeof(ShouldExistFilter<SchoolSubject>))]
public async Task<IActionResult> Edit(SchoolSubjectModel model)
{
// Some logic here
}
推荐阅读
- apache-kafka - kafka流应用程序上的InvalidProducerEpochException循环
- python - Python 上下文管理器:是否可以修改 __exit__ 中的错误对象?
- javascript - 当我下载附件文件时,我收到 IIS HTTP 错误 403.7
- python - Django 可以发送“重置密码”邮件但不能使用“send_mail”
- python - 不使用 wordcloud 库在 Python 中制作 Wordcloud
- javascript - 获取 InvalidCiphertextException: null 使用 aws 解密
- python - 在 jupyter notebook 中绘制 3d 分割的预测
- c++ - Arduino“RGB”灯不闪烁
- python - 以 GitHub 为源的 CDK Codepipeline
- javascript - 带有 2 个必填字段和任意 3 个键中的 1 个必填项的 Joi 验证