Search code examples
c#asp.net-mvcsimple-injector

How to use Simple Injector in an Asp.Net MVC helper method


I have a simple Asp.net MVC helper method in App_Code.

@helper ApprovedStatus(TimeWorkedEntry entry)
{
   if (!entry.Authorised)
   {
    var approvers =   <<get list of approvers from service here >>

    <a tabindex="0"
       role="button"
       class="exclamation"
       data-html="true"
       data-toggle="popover"
       data-trigger="focus"
       title="<b>Not yet approved</b>"
       data-content="@approvers">
        !
    </a>
}
}

My services are normally injected into the controllers within my application by Simple Injector.

What i cannot workout is how to get an instance of my services injected into a helper method. What is it I am missing?


Solution

  • You're missing nothing. Views should be dumb and should especially not have any logic or call any services. That's something that should be in the controller.

    So in your case, the controller should pass the list of approvers on to the view through the view model. The view can pass this information on to the helper method.

    This keeps the code clean, simple and testable.