Wednesday, May 22, 2019

Injecting Service into Asp.Net Core Action Methods

In the previous post we saw on how to inject a service to the MVC controller. This might not be needed always, there are cases where we will need the service only for one action method in the controller. In this post we shall see on how to inject a service to one of the action methods in a controller.

The service and the service registration in the startup remains the same, instead of injecting the service in the controller’s constructor. When injecting the service in the action method we need to use the [FromServices] attribute.  We will inject the service in the action method as follows.

    public class UserServiceController : Controller
    {
        IUserService userService;
        public UserServiceController()
        {
        }
        //
        public async Task Index([FromServices] IUserService _userService)
        {
            userService = _userService;
            return View(await userService.GetUsers());
        }
    }

That’s it now the service will be injected directly to the action method and only this action method will have access to the service. In this case the Index method will use the service to get the list of users and pass it on to the view for display.


Search Flipkart Products:
Flipkart.com

No comments: