簡體   English   中英

如何從 C# 代碼正確使用 Scoped 服務

[英]how to properly use Scoped service from c# code

我使用 blazor 服務器端,因此嘗試使用 AddScoped 而不是 AddSingleton,因為該對象是基於每個用戶使用的。 我嘗試盡可能多地拆分剃刀頁面和 c# 代碼,因為我發現這更干凈。

我使用添加范圍服務

Services.AddScoped<Services.ManageUserService>();

在 Startup 類的 ConfigureServices 函數中。

我現在的問題是從任何 .cs 文件正確訪問服務(保存我的 .razor 頁面的邏輯)

我試圖做這樣的注射:

[Inject]
public Services.ManageUserService manageUserService { get; set; }

然后使用(例如用戶名)訪問范圍對象:

manageUserService.User

這有效。 我的問題是,如果我添加一個只在范圍服務中運行一次的打印,它會在每次重新加載或更改頁面時運行。

例如,假設我這樣做:

public class ManageUserService
{
    public string User { get; private set; }

    private bool LoadedStartup = false;

    public ManageUserService() => SetupUser();

    private void SetupUser()
    {
        if (!LoadedStartup)
        {
            User = "me";
            LoadedStartup = true;
            System.Diagnostics.Debug.Print("User:" + User);
        }
    }
}

然后我使用以下方法從多個 .cs 文件中訪問該類:

[Inject]
public Services.ManageUserService manageUserService { get; set; }

打印“用戶:我”應該只在鎖定 bool LoadedStartup更改時發生一次,問題是每次發生注入時我都會得到打印(在更改頁面等)

我究竟做錯了什么? AddScoped() 不是假設為每個客戶端添加一個“singelton”實例嗎? 我是否錯誤地訪問了它?

我無法從單獨的 .cs 和 .razor 頁面中找到任何使用 AddScoped 的示例,只能直接從 .razor 頁面中找到,然后使用@inject完成。

我處於同樣的情況:

1.- 添加范圍服務:

Services.AddScoped<Services.ManageUserService>();

2.- 然后,為了每個用戶擁有一次真正的范圍實例,在 _Hosts.cshtml 中:

<app>
 <component type="typeof(App)" render-mode="Server" />
</app>

3.- 現在我自己發現的技巧,例如 App.razor 中的作用域服務

@inject Examples.ViewModels.MainViewModel Main;
@inject Examples.ViewModels.ChildViewModel Child;
@inject Examples.ViewModels.LayoutViewModel Layout;
@inject Examples.ViewModels.TreeViewModel Tree;
@{

Child.Main = Main;
Tree.LayoutViewModel = Layout;
}

4.- 如果你在構造函數中有類似的東西:

public class MainViewModel
{
  public static MainViewModel Instance;
  public MainViewModel()
  {
  Instance = this;
 }

}

您可以從代碼中的任何位置訪問您定義為服務的任何類。

 MainViewModel.Instance...

我在我的博客上發布了它: https : //expediteapps.net/2020/02/18/scoped-viewmodels-instanced-once-on-start/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM