liveBook · Manning

ServiceFilterAttribute

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

ServiceFilterAttribute is an ASP.NET Core MVC attribute that obtains a filter and its dependencies from the dependency-injection container.

ServiceFilterAttribute lets an ASP.NET Core MVC action or controller use a filter whose instance and dependencies come from the dependency-injection container. Register the filter and its dependencies, then apply the attribute where the filter should run. section 22.3 section 22.4

Applying a registered filter

Register the filter with DI: builder.Services.AddTransient<EnsureRecipeExistsFilter>(); Then decorate an action: [ServiceFilter(typeof(EnsureRecipeExistsFilter))] public IActionResult Index() => Ok(); The filter can receive services such as RecipeService through its constructor. section 22.3

Use a separate filter class for behavior and an attribute for placement. This avoids the limitation that C# attributes cannot receive ordinary service dependencies in their constructors and are created as singleton instances. 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 filter-attribute separation, registration, and runtime creation, but does not detail the complete filter pipeline.
Examples
Uses EnsureRecipeExistsFilter, RecipeService, AddTransient registration, and an Index action decorated with ServiceFilterAttribute.
What it assumes
Assumes MVC filter and dependency-injection concepts while explaining why attributes cannot directly receive ordinary service dependencies.
What you can do after
Apply ServiceFilterAttribute to use a registered dependency-injected filter on an MVC action or controller.
How it connects
Connects dependency injection with MVC filters, IActionFilter, IFilterFactory, and TypeFilterAttribute.

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.