Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET Core 2.0 MVC Dependency Injection in Views

0.00/5 (No votes)
28 Aug 2017 1  
How to inject and use services in ASP.NET Core MVC views. Continue reading...

Problem

How to inject and use services in ASP.NET Core MVC views.

Solution

Update Startup class to add services and middleware for MVC:

public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddScoped<ILookupService, LookupService>();
            services.AddMvc();
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Add a service:

public interface ILookupService
    {
        List<SelectListItem> Genres { get; }
    }

    public class LookupService : ILookupService
    {
        public List<SelectListItem> Genres
        {
            get
            {
                return new List<SelectListItem>
                {
                    new SelectListItem { Value = "0", Text = "Thriller" },
                    new SelectListItem { Value = "1", Text = "Comedy" },
                    new SelectListItem { Value = "2", Text = "Drama" },
                    new SelectListItem { Value = "3", Text = "Romance" },
                };
            }
        }
    }

Add a controller, returning ViewResult:

public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

Add a view to inject and use the service:

@using Fiver.Mvc.DependencyInjection.Models.Home
@inject ILookupService Lookup

<select name="genres">
<option value="-1">--Select Genre--</option>@foreach (var item in Lookup.Genres)
    {
<option value="@item.Value">@item.Text</option>}
</select>

Discussion

In ASP.NET Core dependency injection is not limited to middleware, controllers and models, etc. Views can also benefit from the services configured in the service container.

There are few options to provide data and behaviour to the view, e.g., ViewData, ViewBag, custom types (View Models) and custom services (via dependency injection). It is best practice to provide the data via a dedicated View Model, which among other benefits, provides strongly typed access to data in views.

Injecting services in views are useful for scenarios where you want to reuse behaviour across multiple views. For instance, to provide lookup data for dropdowns or lists in views.

@inject directive is used to inject services into views. Its syntax is:

@inject service-type variable-name

Note that variable name would be used in Razor with @ symbol e.g. @Lookup, where Lookup is the variable name.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here