I want to resolve some dependencies at a TagHelper
and I have read here that I must register the ITagHelperActivator
interface.
I tried that with the following code:
services.AddSingleton<ITagHelperActivator>(new SimpleInjectorTagHelperActivator(container))
But I get the following error:
ActivationException: The constructor of type UrlResolutionTagHelper contains the parameter with name 'urlHelperFactory' and type IUrlHelperFactory that is not registered. Please ensure IUrlHelperFactory is registered, or change the constructor of UrlResolutionTagHelper.
When I register IUrlHelperFactory
with UrlHelperFactory
then an other dependency is missing and I get an error for that too.
I guess I am doing something wrong, I don't want to register the complete framework.
This won't work. By replacing the default tag helper activator, you redirected the resolution of all tag helpers to Simple Injector, but there are built-in tag helpers and they require the built-in container to be resolved.
Instead, v3.3 of the SimpleInjector.Integration.AspNetCore.Mvc NuGet package allows you to register a custom tag helper activator using the AddSimpleInjectorTagHelperActivation
extension method as follows:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSimpleInjectorTagHelperActivation(container);
// rest of your configuration
}
The extension method takes care of the filtering of tag helpers. When a requested tag helper is located in an assembly starting with "Microsoft", the request for the tag helper is forwarded to the built-in tag helper activator. Otherwise the supplied container
is requested to create the type.
You can override this default behavior by supplying a custom predicate to the AddSimpleInjectorTagHelperActivation
method:
services.AddSimpleInjectorTagHelperActivation(container,
type => type.Namespace.StartsWith("MyApplication"));
Applying the predicate becomes required when you start using 3rd party libraries that plug-in their own tag helpers. In that case the default filter for tags in the "Microsoft" namespace will fail.
Alternatively you can also use the SimpleInjectorTagHelperActivator
directly, but note that this is more complicated to register correctly. You should typically use the AddSimpleInjectorTagHelperActivation
extension method instead:
services.AddSingleton<ITagHelperActivator>(p =>
new SimpleInjectorTagHelperActivator(
container,
type => type.Namespace.StartsWith("MyApplication"),
new DefaultTagHelperActivator(p.GetService<ITypeActivatorCache>())));