Home > Mobile >  How can i define gloabal C# code classes in ASP.NET Blazor which functions can be called from each p
How can i define gloabal C# code classes in ASP.NET Blazor which functions can be called from each p

Time:06-28

I have a Blazor application where I program the code of each razor page in the related xxx.razor.cs Class in C#. I have the case that I use common functions in this C# codes. So instead of repeating the common functions in each class, I want to define a common class, and then call the function from each class. How can I do that? I have tried it like in a C# desktop application but it didn't work.

Commonclass test = new Commonclass();
test.CommonFunction();

CodePudding user response:

I don't know why but after trying for hours I see my error always just when I have posted my question. I had copied the common class from another directory. I forgot to correct the namespace. After correcting it worked.

CodePudding user response:

I think the accepted way to do this is dependency injection. Either a scoped or singleton service.

Program.cs

builder.Services.AddSingleton<Commonclass>();

Razor Page

[Inject] Commonclass test { get; set; }

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    test.CommonFunction();
}
  • Related