首页 > 解决方案 > 从 DI 容器中注册具有多种类型的通用动作过滤器

问题描述

我正在研究一个Asp.net core 5有针对性的.net 5. 我用了Action filteras generic。如果任何其他 对象model在. 如果对象存在或不存在,则泛型类型将替换为要签入的实体名称。IdIdTEntityTEntity

我尝试了什么:

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
}

问题: 当我尝试注册ShouldExistFilterinConfigureServices方法时,我必须将它注册到可能与 the 一起使用的所有实体中,filter这对我来说不实用,因为我有很多实体。

现在我应该这样做:

services.AddScoped<ShouldExistFilter<SchoolSubject>>(); 

services.AddScoped<ShouldExistFilter<Student>>();  
      
services.AddScoped<ShouldExistFilter<Absence>>();

...

问题:

如何注册ShouldExistFilter一次DI Container并与任何一次一起使用Type?或者有什么办法可以到达我的对象?

标签: c#asp.net-coredependency-injectioncustom-action-filter

解决方案


除了服务过滤器属性,您还可以使用该[TypeFilter]属性来创建具有依赖关系的过滤器,而无需向 DI 容器本身注册该过滤器:

[TypeFilter(typeof(ShouldExistFilter<SchoolSubject>))]
public async Task<IActionResult> Edit(SchoolSubjectModel model)
{
    // Some logic here
}

推荐阅读