In a Razor view (.cshtml), what do the @using, @inject and @functions directives add to the generated class, and how does @code differ in a component?
answer
- every Razor file becomes a class
- a property filled from DI
- members, not locals
- the component spelling
basics
~20 sRazor compiles a view into a class: @using adds a C# using, @inject Type Name adds a property resolved from the request's services, and @functions adds class members; @code is the component-only spelling of @functions.
solid answer
~40 sRazor turns each file into a C# class whose render method writes the markup, and directives change that class. `@using System.Globalization` becomes a `using` directive. `@inject SupportInfo Support` becomes a public `Support` property marked for injection; when the view is activated it is resolved with `GetRequiredService` from the request's services, so an unregistered type throws `InvalidOperationException` at render, not at build. `@functions { }` adds fields, properties, methods and nested types to the class, unlike `@{ }`, whose variables are locals of the render method. In a `.razor` component `@code { }` is the recommended alias of `@functions`; in a `.cshtml` view `@code` is not a directive, so it is read as an expression and fails with CS0103.
code
razor · 12 lines@using System.Globalization
@inject SupportInfo Support
@{
var lines = new[] { new Line("A-1", 2, 9.50m), new Line("B-2", 1, 20m) };
}
<p>Total: @FormatTotal(lines)</p>
<p>Questions? Write to @Support.Email</p>
@functions {
private static string FormatTotal(IEnumerable<Line> items) =>
items.Sum(i => i.Qty * i.Price).ToString("0.00", CultureInfo.InvariantCulture);
}go deeper
Recall that @using imports a namespace, @inject Type Name gives the view a service, and @functions or @code add members.
Explain what each directive generates: a using line, a property filled from the request's services, and class members rather than render-method locals.
Diagnose a render-time InvalidOperationException from an unregistered @inject, and keep views from accumulating logic in @functions.
Decide which services views may inject, such as localization and formatting, and keep domain data flowing through models so views stay thin and testable.
## Every Razor file becomes a class Razor is compiled. Each `.cshtml` view becomes a class deriving from `RazorPage<TModel>`, each Razor Page derives from `Page`, and each `.razor` component derives from `ComponentBase`. The markup turns into calls such as `WriteLiteral(...)` and `Write(...)` inside a render method (`ExecuteAsync` for views). **Directives** are the lines that change the class itself rather than what it writes. They must start a line: on the .NET 10 SDK, `<p>@functions</p>` failed with `RZ2005: The 'functions' directive must appear at the start of the line`. ## `@using`: imports for the generated code `@using System.Globalization` adds `using System.Globalization;` to the generated file, so the view can name `CultureInfo` without qualification. In a Razor component, `@using` also decides which **components** are in scope as tags. Repeating the same imports in every file is avoided with a shared imports file, covered with views and layouts. Note that `@using (...) { }` with parentheses is a different thing: a C# `using` statement written as a control structure, used for helpers that open and close a region. ## `@inject`: a property filled from dependency injection The syntax is `@inject <type> <name>`. In the build output for `@inject SupportInfo Support`, the generated class gained: - a `public SupportInfo Support { get; private set; }` property; - a `[RazorInject]` marker attribute on it. When the view is activated, ASP.NET Core 10's property activator fills every marked property with `HttpContext.RequestServices.GetRequiredService(...)`. That has three consequences: 1. **Scoped services resolve per request**, the same instance a controller in that request would get. 2. An **unregistered type** builds fine and then fails at render with `InvalidOperationException: No service for type '...' has been registered.` 3. The built-in `Html`, `Url`, `Component` and `Json` properties are injected the same way, so a view can replace the default HTML helper by injecting its own type under the name `Html`. `@inject` suits presentation services such as localizers, formatting helpers or option lists for a form. Data the page is about should still come from the controller or page model. ## `@functions` versus `@{ }` Both hold C#, but they land in different places: | | `@{ ... }` code block | `@functions { ... }` | |---|---|---| | Becomes | statements in the render method | members of the generated class | | Can declare | locals, local functions | fields, properties, methods, nested types | | Lifetime | one execution of the render method | one instance of the view class | | Allowed in | views, pages, components | views, pages, components | A method in `@functions` may contain markup and act as a small template, and it is callable from any expression in the file. The view engine creates a fresh view object for each render, so `@functions` fields are not a cache shared across requests. ## `@code` in components, and the wrong-file trap In a `.razor` component, `@code { ... }` adds members exactly like `@functions`; the reference calls it an alias and recommends it, and a component may have several `@code` blocks. The trap runs the other way: - in a `.cshtml` view `@code` is **not** a directive; Razor reads `@code` as an implicit expression, and the .NET 10 SDK build failed with `CS0103: The name 'code' does not exist in the current context`; - `@functions` compiles in both file types. ## The other class-shaping directives A few more directives edit the class in the same spirit: `@attribute [Authorize]` adds an attribute, `@implements IDisposable` adds an interface, `@inherits` sets the base class, and `@namespace` sets the namespace. Other directives are tied to one file type and covered with it: `@model` and `@section` with views and pages, `@page` with Razor Pages and routable components, and `@rendermode` with components. ## Reading the generated class When a directive's effect is unclear, look at the code. Setting `EmitCompilerGeneratedFiles` to `true` in the project file makes the build write the generated sources under the `obj` folder's `generated` directory. There you can see the `using` lines that `@using` added, the `[RazorInject]` property behind each `@inject`, the `@functions` members sitting beside the render method, and every `Write` and `WriteLiteral` call the markup became. ## Habits - Keep `@functions` small; a growing block is a sign the logic wants a real class or a view model. - Register every injected type, and remember a missing registration surfaces only when the view renders. - Use `@code` in components and `@functions` in views, and never copy one into the other blindly.
- In a Razor view, what happens if @inject names a type that is not registered in the service container?The view still compiles, because `@inject` only declares a property. When the view is activated, the property is resolved with `GetRequiredService` from the request's services, so rendering throws `InvalidOperationException: No service for type '...' has been registered.` The error shows up on the first request that renders that view.
- Why does @code { } fail in a .cshtml view when it works in a .razor component?`@code` is a directive only in Razor components, where it is the recommended alias of `@functions`. In a `.cshtml` view Razor does not know it as a directive, so it reads `@code` as an implicit expression naming a variable `code`, and the build fails with CS0103. Use `@functions { }` in views and pages.
- @functions and @{ } are interchangeable; both declare locals of the render method.
- A missing @inject registration is caught when the project builds.
- @code works in .cshtml views exactly as in components.
- @inject creates a new service instance on every property access.
- Fields in @functions persist across requests like a static cache.