Click here to Skip to main content
15,881,424 members
Articles / Web Development / ASP.NET

ASP.NET Core 2.0 MVC Dependency Injection in Views

Rate me:
Please Sign up or sign in to vote.
1.80/5 (2 votes)
28 Aug 2017CPOL 5.2K   3  
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:

C#
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:

C#
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:

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

Add a view to inject and use the service:

ASP.NET
@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:

C#
@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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --