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 Genres { get; }
- }
-
- public class LookupService : ILookupService
- {
- public List Genres
- {
- get
- {
- return new List
- {
- 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 the data and behaviour to the View, for 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 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,
- @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.
Source Code
GitHub