liveBook · Manning

TypeFilterAttribute

As explained in ASP.NET Core in Action, 3e

TypeFilterAttribute is an ASP.NET Core MVC attribute that creates a filter through dependency injection while requiring registration only of its dependencies.

TypeFilterAttribute lets MVC and Razor Page filters use dependency injection even though C# attributes cannot receive ordinary constructor dependencies. It separates the filter’s behavior from the attribute that selects where the behavior applies. section 22.3

Use the pattern when a filter needs application services:

  • Put filter behavior in a separate filter class, such as EnsureRecipeExistsFilter, and inject services such as RecipeService through its constructor. section 22.3
  • Apply a separate attribute derived from TypeFilterAttribute to controller classes or action methods. section 22.3
  • Register the filter’s dependencies with the DI container; unlike ServiceFilterAttribute, TypeFilterAttribute does not require registering the filter itself. section 22.4
  • Avoid resolving services manually from the request context when constructor injection can express the dependency directly. section 22.3

Checking that a recipe exists

EnsureRecipeExistsFilter implements IActionFilter and receives RecipeService in its constructor. Its action-executing method reads the recipe identifier, checks existence, and can set a NotFoundResult. EnsureRecipeExistsAttribute supplies the attribute-based application point through TypeFilterAttribute. section 22.3

Figure 22.3 The framework scans your app on startup to find both filters and attributes that implement IFilterFactory. At runtime, the framework calls CreateInstance() to get an instance of the filter.
CH22_F03_Lock3

The framework discovers filter factories during startup and calls CreateInstance at runtime to obtain the filter instance. section 22.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains attribute limitations, split filter design, runtime creation, and registration differences between TypeFilterAttribute and ServiceFilterAttribute.
Examples
Demonstrates EnsureRecipeExistsFilter using RecipeService to return NotFoundResult when a recipe does not exist.
What it assumes
Assumes familiarity with MVC filters and dependency injection while separating attribute usage from filter implementation.
What you can do after
Apply TypeFilterAttribute to custom filters that require constructor-injected services without registering the filter itself.
How it connects
Connects dependency injection with MVC filters, IActionFilter, IFilterFactory, ServiceFilterAttribute, and request-pipeline short-circuiting.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.