[英]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.而不是在每个 razor 页面上放置这些行。 What's the idiomatic way to do it for Blazor?
Blazor 的惯用方法是什么? A base class (how?) or do some tricks in
_Host.cshtml
?一个基本的 class (如何?)或在
_Host.cshtml
中做一些技巧?
A base class (how?)
一个基础 class(如何?)
Create a base class:创建一个基础 class:
public class MyBase : ComponentBase
{
private MyClass _myclass;
protected virtual MyClass MyClass => _myclass ?? ... ;
}
And then use the @inherits
directive to extends the base class:然后使用
@inherits
指令扩展基础 class:
@page "/counter"
@inherits MyBase
<h1>Counter</h1>
...
Add MyClass
as scoped service and inject it wherever you want to use.将
MyClass
添加为范围服务并将其注入到您想要使用的任何位置。
Startup.cs启动.cs
service.AddScoped<MyClass>()
Now you can inject same instance in every page using @inject
directive.现在您可以使用
@inject
指令在每个页面中注入相同的实例。
Index.razor索引.razor
@inject MyClass myClass
https://docs.microsoft.com/en-us/aspnet/core/blazor/dependency-injection https://docs.microsoft.com/en-us/aspnet/core/blazor/dependency-injection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.