使用 DI 容器中的多种类型注册通用 Action Filter

Register generic Action Filter with multiple types from DI container

我正在研究 Asp.net core 5 目标 .net 5。 我使用 Action filter 作为 generic。 此操作过滤器将检查 modelId 是否有任何其他对象在 TEntity 中具有相同的 IdTEntity 是通用类型,如果对象存在与否,将替换为要签入的实体名称。

我试过的:

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
}

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

现在我应该做的:

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

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

...

问题:

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

就像任何通用注册一样,您将其注册为类型

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

除了服务过滤器属性,您还可以使用 [TypeFilter] attribute,这将允许您创建具有依赖项的过滤器,而无需在 DI 容器本身中注册该过滤器:

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