I went back and forth over 10 times with Chat GPT in an endless loop of CS7036 errors on this. I have a Blazor project where I created a custom abstract page class MyPage
subclassing ComponentBase, that I then subclass for all my razor pages. This is so I can put common code on all my pages.
I would like to inject the NavigationManager into this MyPage
class, so that all my pages can access some data gleaned from it (namely the current route for now).
So, here is what I tried: 2 approaches, neither worked.
APPROACH 1
On the MyPage
class, I tried injecting navmanager like this:
public class MyPage : ComponentBase
{
protected NavigationManager NavigationManager { get; set; }
protected MyPage(NavigationManager navManager)
{
NavigationManager = navManager;
}
}
Then, in my razor page:
@page "/example"
@inherits MyPage
@code {
[Inject]
protected NavigationManager NavigationManager { get; set; }
}
APPROACH 2
This approach consists of creating a service, adding it to the app in Program.cs, but still the page gives me the error message.
Here’s what Chat GPT says:
Create a service to provide NavigationManager:Create a singleton service that provides access to NavigationManager.
public class NavigationManagerService
{
public NavigationManager NavigationManager { get; }
public NavigationManagerService(NavigationManager navigationManager)
{
NavigationManager = navigationManager;
}
}
Register the service as a singleton in your application’s Startup.cs or equivalent:
services.AddSingleton<NavigationManagerService>();
Inject NavigationManagerService into the abstract class:Modify the abstract class to accept NavigationManagerService instead of directly injecting NavigationManager.
public abstract class MyPageClass : ComponentBase
{
protected NavigationManager NavigationManager => NavigationService.NavigationManager;
protected NavigationManagerService NavigationService { get; }
protected MyPageClass(NavigationManagerService navigationService)
{
NavigationService = navigationService;
}
}
Inherit from the abstract class in your Razor component and inject NavigationManagerService:
@page "/example"
@inherits MyPageClass
@code {
protected override void OnInitialized()
{
base.OnInitialized();
}
}
With this setup, the NavigationManagerService will handle providing the NavigationManager. The abstract class will accept NavigationManagerService, and your Razor component will inherit from this abstract class, thereby indirectly accessing NavigationManager via NavigationManagerService. This should resolve the CS7036 error.
Of course, both approaches don’t eliminate the error and won’t let me build.
Does anyone have a way of accomplishing this?