JaSHin
JaSHin

Reputation: 277

Razor helper with Dependency injection

Is it possible to make Razor helpers with dependency injection to services? Or call some services from Razor view?

Thanks

Upvotes: 4

Views: 2585

Answers (1)

DiskJunky
DiskJunky

Reputation: 4991

As of .NET Core, yes, they've added support for it; https://learn.microsoft.com/en-us/aspnet/core/mvc/views/dependency-injection

E.g., it allows you to do something like;

@using System.Threading.Tasks
@using ViewInjectSample.Model
@using ViewInjectSample.Model.Services
@model IEnumerable<ToDoItem>
@inject StatisticsService StatsService

You'll note the @inject there at the bottom. The syntax is;

@inject <type> <name>

You'll also need to make sure that the type you want to inject is in your ConfigureServices class in Startup.cs

Upvotes: 3

Related Questions