【问题标题】:How to use the same singleton instance in Razor pages?如何在 Razor 页面中使用相同的单例实例?
【发布时间】:2020-01-27 02:28:23
【问题描述】:

我正在编写一个 ASP.NET Core 应用程序并遇到了一个特殊的问题,即我的 Razor 页面似乎使用与应用程序的其余部分不同的单例实例。

该问题通过在 Razor 页面中显示服务的 List 属性中没有项目为空而表现出来,即使页面处理程序已添加项目也是如此。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>();
    services.AddSingleton<MyService>(new MyService());

    services.AddRazorPages();
}
public class MyService
{
    public int[] Items { get { return this.items.ToArray(); } }

    private List<int> items = new List<int>();

    public MyService() {}

    public void Add(int i) => this.items.Add(i);
}
public async Task<IActionResult> OnPostAddAsync(MyService myService)
{
    myService.Add(1);
}
@page
@inject MyService myService
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<a asp-page-handler="Add">Add</a>
<p>
    @myService.Items.Count() - always 0
</p>

调试还会显示私有列表在 Razor 页面中没有任何项目,即使它在其他地方也是如此。


据我了解,单身人士应该只有一个实例,而不是多个。

我尝试使用私有构造函数、静态实例获取器和添加为 AddSingleton&lt;MyService&gt;(f =&gt; MyService.GetInstance()) 的服务来实现单例模式,但是遇到了依赖注入无法创建实例的异常。

模型绑定的复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数。


我做错了什么?如何让 Razor 页面使用相同的单例实例?

【问题讨论】:

  • 计数增加的唯一方法是调用Add 方法,然后执行razor 中的代码。另外,它必须在同一个请求中完成。设置断点并调试,看看是否发生这种情况。
  • @CodingYoshi 我认为单身人士在多次请求中幸存下来?
  • 你为什么说单例,是什么让你认为你有一个单例?是services.AddSingleton&lt;MyService&gt;吗?我没用过。如果这与单例的工作方式相同,那么如果调用 Add 并在每次调用 Add 后执行剃刀页面,则计数将增加。
  • @CodingYoshi docs.microsoft.com/en-us/aspnet/core/fundamentals/… 听起来像 AddSingleton&lt;T&gt;(T) 做我想做的事,不是吗?
  • 是的。我之前的评论仍然适用。

标签: c# asp.net-core razor dependency-injection singleton


【解决方案1】:

解决方案是在IndexModel 构造函数中注入服务,而不是作为页面处理程序方法的参数。

private readonly MyService _myService;

public IndexModel(MyService myService)
{
    _myService = myService;
}

public async Task<IActionResult> OnPostAddAsync()
{
    _myService.Add(1);
}

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多