What are the common directives (@inject, @using, @inherits, @implements, @namespace, @attribute) and what does each do?
Last updated
Razor directives configure how a component is compiled and what it has access to. These common ones handle dependency injection, namespace imports, inheritance, interfaces, and applying attributes to the generated class.
@inject: Injects a service from DI into a property, e.g.@inject NavigationManager Nav.@using: Imports a namespace, just like a C#using; put shared ones in_Imports.razor.@inherits: Sets a custom base class instead ofComponentBase(e.g. a shared base with common logic).@implements: Declares that the component implements an interface, e.g.@implements IDisposableto clean up resources.@namespace: Overrides the generated class's namespace, decoupling it from the folder structure.@attribute: Applies a .NET attribute to the component class, e.g.@attribute [Authorize].
- https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/dependency-injection?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/architecture/blazor-for-web-forms-developers/components
- https://blazor-university.com/components/literals-expressions-and-directives/directives/