How to create and inject a user specific singleton class throughout the whole application?

Viewed 2581

I'm trying to create a user-specific specific singleton object on Blazor serverside application. Is there a way we can achieve this using .NET Core dependency injection system? I've tried below code. I've created SingletonTest class.

public class SingletonTest
{
    private int _counter;
    public int Counter { get { return ++_counter; } }
}

Injected the SingletonTest class in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<SingletonTest>();
}

Accessing the Counter property in index.razor file

@page "/"
@inject SingletonTest singletonTest;
Counter: @singletonTest.Counter

When I try to access the index page in two different browsers, both are accessing the same single instance of SingletonTest class. I there a way I can make this user-specific singleton? once the browser is closed the server need to dispose the user-specific singleton object and call the garbage collector.

1 Answers
Related