Service Injection into View in ASP.NET Core

This blog is about how dependency is injected directly into view. Let us look at it using a small example.

The following is a ColorListService class that returns a list of strings.


Put all your services in a separate folder called Services. So this will help you maintain a project structure


public class ColorListService
    public List<string> GetColors()
        return new List<string>() { “Red”, “Blue”, “Green”, “Yellow”, “Violet” };

Before you can use a service, you must register for the service. See ASP.NET Service Scope for more information


public void ConfigureServices(IServiceCollection services)

The following is a view code. Here the ColorListService is injected using @Inject Directive. Finally a list of colors is listed using foreach.


    Layout = null;
    ViewData[“Title”] = “Service Injection into View”;

@inject SampleMVCApplication.Services.ColorListService  colors

<h4>Service Injection into View in ASP.NET Core</h4>

@foreach (string item in colors.GetColors())

Below is a HomeController code. It has a ServiceDemo() action which will render a ServiceDemo view.


public class HomeController : Controller
    public IActionResult ServiceDemo()
         return View();

The following is the output of the above code

Service Injection into View

This blog explains how to inject the service directly into the view with a small example.

If you have any questions, please leave a comment below.