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.