首页 > 解决方案 > 我应该使用临时服务和存储库进行用户身份验证吗?

问题描述

我的 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 保持为单例?

标签: asp.net-mvc.net-coreidentityserver4

解决方案


通常,如果以下任何一项为真并且所讨论的类是线程安全的,则您只想在 Web 应用程序中使用单例:

  • 底层资源的构建(例如到分布式缓存的连接)是昂贵的
  • 您需要在应用程序的持续时间内保持内存状态
  • 您需要序列化对资源的访问(例如,仅附加文件)

在您的情况下,这些都不是真的,所以范围或瞬态完全没问题。


推荐阅读