Glimpse from the TagHelpers Future - Adding TagHelpers via Dependency Injection
Last week when I asked Damian Edwards how to add TagHelper via dependency injection (DI), he referred me to a new feature called TagHelperComponent that will be shipped in ASP.NET Core 2.0.
Perhaps it is too early, but I would like to give you some glimpse of the new TagHelperComponents
What are TagHelperComponents?
TagHelperComponents are effectively to add TagHelpers via DI system, however they are not fully fledged TagHelpers, TagHelperComponents enable you to have some certain types of TagHelpers like things light up inside the application automatically.
Where are TagHelperComponent fits?
As we know TagHelpers should participate in the view compilation, so
that's why you can't put them in DI, and the should be declared in the razor
file. Now we can TagHelperComponents to add TagHelpers into DI with some limitations.
As Damian Edwards said:
In ASP.NET Core 2.0 the TagHelperComponents specifically will be enabled in two places: head & body tags
Why these places only?!! If you are using an ASP.NET Core for time you will probably notice that default template has several Application Insights scripts, which is similar to this:
also there are few other places. The issue that there are many profiling & diagnostics libraries such as Glimpse, Application Insights and much more, need to inject some neccesary scripts in the
body tags. So
come for rescue to automate the process of injecting needed scripts
& styles, that's I think why ASP.NET Core team have decided to
body tags in 2.0 release.
TagHelperComponent in Action
As I mentioned before that
TagHelperComponent very useful in
profiling & diagnostics libraries, but not only that there are many
other libraries they need sort type of script injection such as Google Analytics .
Surprisingly I worked two months ago on a small project called
This is a part of how the layout file was:
I should use the DI and inject the script where ever I want myself,
but no longer anymore!! today I modified the source code to use the
TagHelperComponent as the following:
After that we can add the
Perhaps what I showed you before is not enough to understand the need of such feature, but what about this!!
this is a snippet from live.asp.net code where Google Analytics required a script to be injected in the
head tag, FYI this just the first part of the entire script needed, the other part in the _AnalyticsBody.cshtml. Of course you wanna need some mechanism to inject these scripts in your behalf :) this is where
You can look to the updated source code for my jsLogger repository on GitHub.