Course contentsShow
← C#
Lesson 1315 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Dependency Injection in Razor

Inject scoped and singleton services directly into views for dynamic data retrieval.

In this lesson, you will learn how to leverage the @inject directive to bring scoped and singleton services directly into your Razor views for real-time data retrieval.

The Power of Direct Injection

Usually, we pass data to a view using a ViewModel. However, there are scenarios—such as displaying system-wide settings, current session metrics, or localized content—where passing data through every controller or page model becomes cumbersome. In Razor, you can bypass the "middle-man" by injecting a service directly into the markup.

When you use @inject, the Razor engine resolves the requested service from the application's built-in Dependency Injection (DI) container. Because this happens during the rendering phase, the view gains direct access to the service’s methods and properties.

Practical Implementation

To inject a service, use the @inject directive followed by the type and a variable name:

@using MyApp.Services
@inject ISystemConfiguration ConfigService

<div class="footer">
    <p>Current Environment: @ConfigService.GetEnvironmentName()</p>
    <p>Copyright Year: @ConfigService.GetDefaultYear()</p>
</div>

Scoped vs. Singleton Considerations

It is vital to understand the lifecycle of the service you are injecting:

  • Singleton: The service is created once and shared across all users. This is perfect for high-level application configuration or static data that doesn't change per request.
  • Scoped: The service is created once per client request. Use this when your service needs to interact with the current user’s context, such as a database context or a specific user-preferences service.

By injecting services directly, you keep your view logic clean and avoid "Model bloat," where your ViewModels grow unnecessarily large just to hold metadata that the view could have fetched on its own. Just remember: keep this technique reserved for supporting services. If your view needs business logic, continue relying on your model for data, as mixing complex logic inside the view can make your components harder to test.

Key Takeaway: Use the @inject directive to directly consume Scoped or Singleton services in your Razor views, allowing you to access site-wide data or request-specific context without cluttering your ViewModels.