ASP.NET Core 2.0 MVC Dependency Injection In Views

Problem

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

Solution

Update Startup class to add services and middleware for MVC.

Add a service

Add a Controller, returning ViewResult.

Add a View to inject and use the service.

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 the data and behaviour to the View, for e.g. - ViewDataViewBag, 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 the data in Views.

Injecting services in Views is useful for scenarios where you want to reuse a behavior 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,

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

Source Code

GitHub

Next Recommended Readings