The _ViewImports file is important and very useful. I discovered this file a while ago when I was needing dependency injection into a View for work. We deal with a large amount of different views (templates), and it immediately felt wrong to have to add dependency injection manually to a number of the views. It would quickly become hard to manage when adding more DI, and/or for different views. Enter the _ViewImports.cshtml file.
Extract from microsoft:
Importing Shared Directives
Views and pages can use Razor directives to import namespaces and use dependency injection. Directives shared by many views may be specified in a common _ViewImports.cshtml
file. The _ViewImports
file supports the following directives:
@addTagHelper
@removeTagHelper
@tagHelperPrefix
@using
@model
@inherits
@inject
@namespace
The file doesn't support other Razor features, such as functions and section definitions.
The _ViewImports.cshtml
file for an ASP.NET Core MVC app is typically placed in the Pages (or Views) folder. A _ViewImports.cshtml
file can be placed within any folder, in which case it will only be applied to pages or views within that folder and its subfolders. _ViewImports
files are processed starting at the root level and then for each folder leading up to the location of the page or view itself. _ViewImports
settings specified at the root level may be overridden at the folder level.