What is the difference between a filter attribute applied directly (like [MyFilter]) and using [TypeFilter]/[ServiceFilter] to apply the same filter class?
Short answer
A filter class can be applied directly as an attribute ([MyFilter]) only if it has a parameterless constructor or its dependencies are resolvable in a way attributes support (attributes can't use full constructor DI directly since they're instantiated by the .NET attribute…
Advertisement
AModel answer
A filter class can be applied directly as an attribute ([MyFilter]) only if it has a parameterless constructor or its dependencies are resolvable in a way attributes support (attributes can't use full constructor DI directly since they're instantiated by the .NET attribute system, not the DI container) -- for filters needing injected services, [TypeFilter]/[ServiceFilter] are required to route instantiation through the DI container instead, since a plain attribute application bypasses DI entirely.
// Direct attribute application: filter must not need DI-injected dependencies
public class SimpleLogFilter : Attribute, IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) => Console.WriteLine("Logged");
}
[SimpleLogFilter]
public IActionResult Get() { ... }
// Needs DI: must use TypeFilter/ServiceFilter instead
[ServiceFilter(typeof(DatabaseAuditFilter))] // DatabaseAuditFilter needs an injected DbContext
public IActionResult Delete(int id) { ... }Real-world example
A team's initial attempt to apply a filter needing an injected ILogger directly as [MyLoggingFilter] fails to compile/resolve correctly, requiring a switch to [ServiceFilter(typeof(MyLoggingFilter))] to properly route construction through DI.
Likely follow-ups
- Why can't attributes use standard constructor dependency injection directly?
- What's the performance overhead difference between direct attributes and TypeFilter/ServiceFilter?
Related topics