[英]How to use the same singleton instance from main appdomain in childs appdomain
[英]How to use the same singleton instance in Razor pages?
我正在编写一个 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<MyService>(f => MyService.GetInstance())
,但是遇到了关于依赖注入无法执行的异常创建一个实例。
模型绑定复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数。
我究竟做错了什么? 如何让 Razor 页面使用相同的单例实例?
解决方案是在IndexModel
构造函数中注入服务,而不是作为页面处理程序方法的参数。
private readonly MyService _myService;
public IndexModel(MyService myService)
{
_myService = myService;
}
public async Task<IActionResult> OnPostAddAsync()
{
_myService.Add(1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.