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.
The framework discovers filter factories during startup and calls CreateInstance at runtime to obtain the filter instance. section 22.3
