[英]How to create and inject a user specific singleton class throughout the whole application?
I'm trying to create a user-specific specific singleton object on Blazor serverside application.我正在尝试在 Blazor 服务器端应用程序上创建特定于用户的 singleton object。 Is there a way we can achieve this using .NET Core dependency injection system?
有没有办法使用 .NET 核心依赖注入系统来实现这一点? I've tried below code.
我试过下面的代码。 I've created SingletonTest class.
我创建了 SingletonTest class。
public class SingletonTest
{
private int _counter;
public int Counter { get { return ++_counter; } }
}
Injected the SingletonTest class in Startup.cs在 Startup.cs 中注入 SingletonTest class
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<SingletonTest>();
}
Accessing the Counter
property in index.razor file访问 index.razor 文件中的
Counter
属性
@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.当我尝试在两个不同的浏览器中访问索引页面时,两者都在访问同一个
SingletonTest
class 实例。 I there a way I can make this user-specific singleton?我有办法制作这个用户特定的 singleton? once the browser is closed the server need to dispose the user-specific singleton object and call the garbage collector.
一旦浏览器关闭,服务器需要处理用户特定的 singleton object 并调用垃圾收集器。
Add Scoped is what you need if you want it to be only available to a single browser instance:如果您希望它仅可用于单个浏览器实例,则添加 Scoped 是您所需要的:
services.AddScoped<YourScopedClass>();
Another thing you can use is a preview Nuget package:您可以使用的另一件事是预览 Nuget package:
Microsoft.AspNetCore.ProtectedBrowserStorage Microsoft.AspNetCore.ProtectedBrowserStorage
the docs for ProtectedBrowserStorage are are about 40% down on this page: https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.1 ProtectedBrowserStorage 的文档在此页面上大约下降了 40%: https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.1
I use the above package here in a Server Side Blazor project called BlazorChat that uses a singleton just like you are to communicate to all the users, but the ProtectedBrowserStorage to store the users password hash, email address and login name. I use the above package here in a Server Side Blazor project called BlazorChat that uses a singleton just like you are to communicate to all the users, but the ProtectedBrowserStorage to store the users password hash, email address and login name.
https://github.com/DataJuggler/BlazorChat https://github.com/DataJuggler/BlazorChat
The site is also live, but no one has signed up but me so far.该网站也是实时的,但到目前为止除了我之外没有人注册。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.