Tag helper components were introduced in ASP.NET Core 2.0. They are a way to use DI for inserting markup in the output. Imagine, for example, inserting JavaScript or CSS files at a specific location in your views.
Tag helper components must implement ITagHelperComponent
and are registered in the DI framework (ConfigureServices
method):
services.AddSingleton<ITagHelperComponent, HelloWorldTagHelperComponent>();
The ITagHelperComponent
interface only specifies a method, ProcessAsync
. Each registered tag helper component will have its ProcessAsync
method called for every tag found on the current view--including layouts--giving it a chance to inject custom tag helpers:
public class HelloWorldTagHelperComponent : TagHelperComponent { public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context.TagName.ToLowerInvariant() == "head") { output.Content.AppendHtml("<script>window.alert('Hello, World!')</script>...