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 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, provide 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:

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

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Mvc.DependencyInjection

Leave a Reply