Kjensen
Kjensen

Reputation: 12374

Inject a service in all ASP.Net Core Razor views

How can I inject a service into all razor views?

In views, where I need to access a service (which stores localized texts), I can inject it like this:

@inject IResourceHelper _resourceHelper

and then I can use it like this...:

<a id="somelink" title="@(_resourceHelper.GetText("somelink-title"))"></a>

Works just fine. However, since I need this in all views (pretty much), I would like to inject it just once - and have it available everywhere.

I have looked towards _ViewImports.cshtml, which seems like a natural fit for something like this - where I already add some taghelpers, like this:

@addTagHelper MyProject.Internationalization.TagHelpers.*, MyProject.Core

I have tried adding an inject-statement there, but it does not make the service available in razor views.

How can I inject a service into all razor views?

Upvotes: 4

Views: 1325

Answers (1)

Jerry Cai
Jerry Cai

Reputation: 939

You just need to add

@inject IResourceHelper _resourceHelper

in Viewimports, then you can use it globally like

<h1 class="display-4">@(_resourceHelper.Actionname().title)</h1>

This works for me, as a sample:

@page
@model PrivacyModel
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<h1 class="display-4">@(MyService.getname().Name)</h1>

Upvotes: 7

Related Questions