In this lesson, you will learn how to manage file-level dependencies and service availability in Razor views and Blazor components using @using, @inherits, and @inject.
When building interfaces in Razor, you often need to bring in external namespaces, define a specific base class, or access services from your dependency injection container. Directives are the special commands that tell the Razor engine how to handle these architectural requirements at the top of your file.
Controlling Dependencies
The @using directive functions exactly like a standard C# using statement. It allows you to reference classes without typing out their fully qualified names. For example, if you are working with data models, adding @using MyApp.Models at the top of your file lets you reference Product instead of MyApp.Models.Product.
Defining Inheritance
By default, Razor files inherit from a base class that provides the core rendering engine. If you need your component or view to extend a specific custom class (perhaps to provide shared UI logic or properties), you use the @inherits directive:
@inherits MyCustomBasePage<TModel>
<h1>Welcome, @User.Identity.Name</h1>
Injecting Services
In modern Blazor development, we rarely instantiate classes manually. Instead, we use the @inject directive to pull services directly into our component. This is how you access your databases, authentication state, or custom business logic services. It declares a property that the dependency injection system populates automatically:
@inject IProductService ProductService
<p>There are @ProductService.GetCount() products available.</p>
When you use @inject, you provide the type of the service followed by a property name. The Razor engine creates a private property behind the scenes, allowing you to use ProductService anywhere within your markup or code blocks. By mastering these three directives, you move from simple markup to a professional, modular architecture where your UI remains clean and your dependencies are managed by the framework.
Key Takeaway: Use @using for namespaces, @inherits for custom base logic, and @inject to bring service dependencies into your component's scope.