I have a website where I want to have a partial view on the page that contains a Singleton service.

I am trying to do this with Razor Pages, and have tried Partial Views and ViewComponents, but haven't gotten the desired experience, probably because I am not implementing correctly.

Here is what I would like to accomplish.

  1. Singleton Service that is shared between the partial view and all other views in app (this login panel where each page needs to access the user name supplied by the service.
  2. Based on state of the service, doing a common process (custom business logic) on each view (if the user is of a certain role, change UI and log differenly)
  3. Not having to wire up DI constructors on each view (can I use a base pagemodel)

I can supply some code if needed but I wanted to see if what I am trying to do is allowed with Razor Pages.

  • 1
    "(...) I wanted to see if what I am trying to do is allowed with Razor Pages.". Have you checked documentation, or looked how projects similar to yours implement this?
    – Mael
    Commented Mar 7, 2018 at 11:39

1 Answer 1


Seems like you would need to inject the required service globally in main _ViewImports.cshtml file (usually under /Views or /Pages folder) like:

@using Microsoft.AspNetCore.Hosting
@inject IHostingEnvironment Environment

You can then call it in any view or partial view like this:

@if (Environment.IsDevelopment())
    <h4>Yep, this is development environment!</h4>

Personally, I use this feature all the time for IViewLocalizer service.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.