Asp.net mvc taghelper and Dependency Injection
I was wondering if you could use Dependency Injection to initialize an Asp.net mvc taghelper. I’ll modify the example used in my previous post Creating a custom taghelper.
Creating a service to inject
public interface IPersonService
{
string GetName();
}
public class PersonService : IPersonService
{
public String GetName()
{
return "PersonService.GetName()";
}
}
Register this class in the DI-system of Asp.net. Add it to services collection in the ConfigureServices method from the Startup class.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPersonService, PersonService>();
}
Modifying the taghelper
[TargetElement("Person")]
public class MyTagHelper : TagHelper
{
IPersonService _personService;
public MyTagHelper(IPersonService personService)
{
_personService = personService;
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Content.SetContent(_personService.GetName());
base.Process(context, output);
}
}
Testing
When I run the application, the DI-system will also inject dependencies for taghelpers.