Advertisement
Intermediate ASP.NET Core, Filters

How do you pass constructor parameters or configuration to a filter class using [TypeFilter] or [ServiceFilter]?

Short answer

[TypeFilter(typeof(MyFilter), Arguments = new object[] { "someValue" })] instantiates the filter via the DI container but lets you pass additional constructor arguments not resolvable from DI.

Save ASP.NET Core mock interview
Advertisement
AModel answer
[TypeFilter(typeof(MyFilter), Arguments = new object[] { "someValue" })] instantiates the filter via the DI container but lets you pass additional constructor arguments not resolvable from DI. [ServiceFilter(typeof(MyFilter))] instead requires the filter itself to be registered in the DI container and resolves it entirely through DI, appropriate when the filter's dependencies are all standard injectable services with no need for additional per-usage arguments.
// TypeFilter: mix DI-resolved dependencies with explicit arguments
[TypeFilter(typeof(RateLimitFilter), Arguments = new object[] { 100 })]
public IActionResult Get() { ... }

// ServiceFilter: filter itself registered in DI, fully resolved from there
builder.Services.AddScoped<AuditFilter>();
[ServiceFilter(typeof(AuditFilter))]
public IActionResult Delete(int id) { ... }
Real-world example
A rate-limiting filter uses TypeFilter with an explicit request-count argument so different actions can apply the same filter class with different limits (100 vs 10) without needing separate filter classes for each threshold.
Likely follow-ups
  • What's the practical difference in DI lifetime behavior between TypeFilter and ServiceFilter?
  • When would a plain filter attribute (no DI needed) be simpler than either approach?
Related topics