【问题标题】:How to use singleton in asp.net core 2.1 with parameter (interface)如何在带参数的asp.net core 2.1中使用单例(接口)
【发布时间】:2019-06-30 03:48:28
【问题描述】:

在启动文件中

services.AddScoped<IUserResponsitory , UserResponsitory>();
services.AddSingleton<IAuthService>(service=>new AuthServiceImpl(
            service.GetService<IUserResponsitory>(),service.GetService<IConfiguration>()));

在 AuthServiceImpl 文件中:

    private IUserResponsitory m_userResponsitory;
    private IConfiguration m_config;
    public  AuthServiceImpl(IUserResponsitory userResponsitory, IConfiguration config) 
    {
        m_config = config;
        m_userResponsitory = userResponsitory;
    }

在 UserResponsitory 文件中。

public class UserResponsitory : Responsitory<Users>,IUserResponsitory
    {
        private DbSet<Users> userEntity;

        public UserResponsitory(MyDBContext context) : base(context)
        {
            userEntity = context.Set<Users>();
        }
    }

下面的错误

一些帮助: help1

help2

你能帮帮我吗?拜托!

【问题讨论】:

    标签: asp.net asp.net-core singleton


    【解决方案1】:

    由于 .NET Core 应用了范围验证,因此您无法在使用单例生命周期 (IAuthService) 注册的服务的构造函数中解析具有范围生命周期(在您的情况下为 IUserResponsitory)的服务。

    因此,您需要将 IAuthService 生命周期更改为作用域。

    services.AddScoped&lt;IAuthService, AuthService&gt;();

    有用的资源:

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2#scope-validation

    https://bartwullems.blogspot.com/2019/02/aspnet-core-scope-validation.html

    【讨论】:

    • 感谢您的回答,因此每个请求只创建一次 Scoped 生命周期服务。我想为我的服务创建单例,在使用登录时保存我的令牌。如果我为该服务使用 Scoped,我将找不到之前创建的令牌。
    • 因此,将您的 IAuth 服务设置为单例意味着数据将在登录的用户之间共享,这是您永远不会想要的。
    【解决方案2】:

    如错误所示,您无法从root provider 解析范围服务。

    如果您更喜欢将IAuthService 用作Singleton,您可以从IServiceProvider 解析服务,例如

    1. Startup.cs

      services.AddScoped<IUserResponsitory , UserResponsitory>();
      services.AddSingleton<IAuthService, AuthServiceImpl>();
      
    2. AuthServiceImpl

      public class AuthService : IAuthService
      {
          private readonly IServiceProvider _serviceProvider;
          private readonly IConfiguration m_config;
          public AuthService(IServiceProvider serviceProvider
              , IConfiguration configuration)
          {
              _serviceProvider = serviceProvider;
              m_config = configuration;
          }
      
          public void Auth()
          {
              using (var scope = _serviceProvider.CreateScope())
              {
                  var db = scope.ServiceProvider.GetRequiredService<IUserResponsitory>();
                  var result = db.Users.ToList();
              }
          }
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 2019-10-07
      • 2019-04-02
      • 2020-10-15
      相关资源
      最近更新 更多