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.

taghelper and dependency injection

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>