asp.net-mvc - 我应该使用临时服务和存储库进行用户身份验证吗?
问题描述
我的 ConfigureServices 部分Startup.cs
如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = services.AddIdentityServer()
.AddInMemoryApiResources(Configurations.ApiResources.GetApiResources())
.AddInMemoryClients(Configurations.Clients.GetClients());
services.AddEntityFrameworkNpgsql();
services.AddDbContext<IdentityDbContext>();
services.BuildServiceProvider();
services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
// Login Service and User Repo Injection
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<ILoginService, LoginService>();
// Connection String Config
services.Configure<ConnectionStringConfig>(Configuration.GetSection("ConnectionStringConfig"));
if (Environment.IsDevelopment())
{
builder.AddDeveloperSigningCredential();
}
}
我正在将我的 loginService 注入到ResourceOwnerPasswordValidator
,我正在将 userRepository 注入到我的 loginService 中。ResourceOwnerPasswordValidator
正在处理我的用户登录的验证。
我最初将我的存储库和 loginService 添加为单例,但出现错误
无法使用单例 userRepository 中的 DbContext 范围实例。
正如您在上面看到的,我将 loginService 和 userRepository 实例都更改为瞬态。这是一种安全的方法吗,还是我应该选择另一种方法?
我的 loginService 使用 userRepository 与数据库通信。但是,如果我将它们添加为单例,
我得到一个不能使用作用域数据库实例
,所以我想我会让整个事情变得短暂。
有没有更好的方法可以让我将 loginService 和 userRepository 保持为单例?
解决方案
通常,如果以下任何一项为真并且所讨论的类是线程安全的,则您只想在 Web 应用程序中使用单例:
- 底层资源的构建(例如到分布式缓存的连接)是昂贵的
- 您需要在应用程序的持续时间内保持内存状态
- 您需要序列化对资源的访问(例如,仅附加文件)
在您的情况下,这些都不是真的,所以范围或瞬态完全没问题。
推荐阅读
- python - OpenCV CascadeClassifier Python内存不足
- dapper - 使用 Dapper 更新请求
- listview - 为列表视图 javafx 设置颜色
- perl - 在无限循环中杀死通过 system() 函数运行的子进程在 perl 中不起作用
- php - Mysqli构造警告,服务器请求客户端未知的身份验证方法[caching_sha2_password]
- c++ - 将清除共享智能指针上的呼叫重置
- ajax - 访问控制允许来源无法识别
- django - Django从用户那里获取数据,离线处理以将CSV发送给用户
- node.js - 如何在 MS Bot Dialog(NodeJS) 中使用 npm 的 readline-Sync 输入屏蔽功能?
- javascript - 表单与仅带有输入的 div 和带有事件侦听器的按钮