Wednesday, May 22, 2019

Injecting Service into Asp.Net Core Controllers

In the previous example we created an interface IUserService and a service class UserService. We also registered the service in the Asp.Net Core startup. In this post we will see on how to inject this service in the constructor of MVC controller and use it to populate the view. To start with let us create a new MVC controller and name it UserServiceController.

In the constructor of the Controller class we will pass a reference to the IUserService. Since we registered this interface with the service class in the startup, the Asp.Net runtime will inject an instance of the UserService class to the controller. Following is the code for the MVC controller.

    public class UserServiceController : Controller
    {
        IUserService userService;
        public UserServiceController(IUserService _userService)
        {
            userService = _userService;
        }
        //
        public async Task<IActionResult> Index()
        {
            return View(await userService.GetUsers());
        }
    }

Now we can create a view for the Index method, which will display the list of users returned by the Action Method, following is the code for the view.

@model IEnumerable<HelloMVC.Models.EFCoreModel.Users>
@{
    ViewData["Title"] = "Index";
}
<h4>UserService - Dependency Injection</h4>
<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Phone)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Email)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Address)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Phone)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.UserId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.UserId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.UserId">Delete</a>
            </td>
        </tr>
    }
    </tbody>
</table>

Build and run the application, the output will be as follows.



Search Flipkart Products:
Flipkart.com

No comments: