简体   繁体   中英

How to use the same singleton instance in Razor pages?

I'm writing an ASP.NET Core app and ran into the peculiar problem that my Razor pages seem to use different singleton instances than the rest of the app.

The problem manifests itself by showing no items in a List property of the service being empty in Razor pages even when items have been added by page handlers.

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>

Debugging also shows the private List to have no items in Razor pages even when it does elsewhere.


From my understanding singletons should only have one instance, not several.

I tried implementing a singleton pattern with a private constructor, a static instance-getter, and the service added as AddSingleton<MyService>(f => MyService.GetInstance()) , but that ran into an exception about dependency injection not being able to create an instance.

Model bound complex types must not be abstract or value types and must have a parameterless constructor.


What am I doing wrong? How do I get Razor pages to use the same singleton instance?

The solution is to inject the service in the IndexModel constructor and not as a parameter to the page handler method.

private readonly MyService _myService;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM