简体   繁体   中英

Common property for all Blazor pages?

I will need to have some properties for every page. For example,

private MyClass _myclass;
protected MyClass MyClass => _myclass ??= InitMyClass();

Instead of putting the lines on every razor page. What's the idiomatic way to do it for Blazor? A base class (how?) or do some tricks in _Host.cshtml ?

A base class (how?)

Create a base class:

public class MyBase : ComponentBase 
{
    private MyClass _myclass;
    protected virtual MyClass MyClass => _myclass ?? ... ;
}

And then use the @inherits directive to extends the base class:

@page "/counter"
@inherits MyBase

<h1>Counter</h1>
...

Add MyClass as scoped service and inject it wherever you want to use.

Startup.cs

service.AddScoped<MyClass>()

Now you can inject same instance in every page using @inject directive.

Index.razor

@inject MyClass myClass

https://docs.microsoft.com/en-us/aspnet/core/blazor/dependency-injection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM