【问题标题】:asp.net core DI only injects singletons, scoped and transient not workingasp.net core DI 只注入单例,作用域和瞬态不起作用
【发布时间】:2017-06-10 21:50:26
【问题描述】:

我被困住了,我似乎无法弄清楚这一点。我有一个带有接口的简单类。我将 EFContext 和 Logger 注入此服务。出于某种原因,无论我如何注册服务,它总是一个单例。我将 Guid 属性放在类上,看看它是否在每个请求中都发生了变化,但它保持不变。

这是 AccountService 类及其接口:

public interface IAccountService 
{
    Account GetAccountByEmailAndPassword(string emailAddress, string password);
}

public class AccountService : IAccountService
{
    private readonly IEFContext _context;
    private readonly ILogger<AccountService> _logger;
    private string _guid;

    public AccountService()
    {
        _context = context;
        _logger = logger;
        _guid = Guid.NewGuid().ToString();
    }

    public Account GetAccountByEmailAndPassword(string emailAddress, string password)
    {
        try
        {
            //get the account
            var account = _context.Account.FirstOrDefault(x => x.EmailAddress == emailAddress);

            //make sure we have an account
            if (account == null)
                return null;

            //generate hash from account
            var accountHash = GeneratePasswordSaltHash(account.Password, account.PasswordSalt);

            //generate hash from credentials passed in
            var passedInHash = GeneratePasswordSaltHash(
                Convert.ToBase64String(HashPassword(password)),
                account.PasswordSalt);

            // TODO: number of failed attempts should lock account etc.
            return accountHash == passedInHash ? account : null;
        } catch (Exception ex)
        {
            _logger.LogError("Exception in AccountService: " + ex.ToString());
            throw;
        }
    }
}

这是我注册服务的方式:

public void ConfigureServices(IServiceCollection services)
{
    // App Settings
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

    // Add DBContext
    var connectionString = Configuration["AppSettings:Data:ConnectionString"];
    services.AddDbContext<EFContext>(options => options.UseSqlServer(connectionString));

    // Add framework services.
    services.AddMvc();

    //  Add DI
    services.AddScoped<IEFContext, EFContext>();
    services.AddScoped<IAccountService, AccountService>();
}

这是 EFContext 类及其接口:

public interface IEFContext
{
    DbSet<Account> Account { get; set; }

    int SaveChanges();
    EntityEntry Update(object entity);
}

public class EFContext : DbContext, IEFContext
{
    public EFContext(DbContextOptions options) : base(options) {}
    public DbSet<Account> Account { get; set; }
}

我可以通过上下文访问数据库和所有内容,但是,一切都是单例的。我首先被告知该问题,因为如果我进入数据库并手动更新帐户上的一些数据,然后再次以代码请求该帐户,则数据将变得陈旧。我认为这是一个上下文问题,但我认为我正在使用 .AddScoped&lt;&gt; 正确配置上下文生命周期,但我无法让它工作。因此,我尝试将_guid 属性添加到AccountService,以确定它是否在每个请求中都得到了更新,但似乎没有。我也试过.AddTransient&lt;&gt;。任何帮助表示赞赏。非常感谢。

编辑 这是我的配置方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));

        loggerFactory.AddDebug();
        loggerFactory.AddSerilog();

        //Token stuff
        // secretKey contains a secret passphrase only your server knows
        var secretKey = "mysupersecret_secretkey!123";
        var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

        var tokenValidationParameters = new TokenValidationParameters
        {
            // The signing key must match!
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = signingKey,

            // Validate the JWT Issuer (iss) claim
            ValidateIssuer = true,
            ValidIssuer = "ExampleIssuer",

            // Validate the JWT Audience (aud) claim
            ValidateAudience = true,
            ValidAudience = "ExampleAudience",

            // Validate the token expiry
            ValidateLifetime = true,

            // If you want to allow a certain amount of clock drift, set that here:
            ClockSkew = TimeSpan.Zero
        };

        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            TokenValidationParameters = tokenValidationParameters
        });

        // Token generator
        var options = new TokenProviderOptions
        {
            Audience = "ExampleAudience",
            Issuer = "ExampleIssuer",
            SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
        };

        app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));

        app.UseMvc();
    }

在我的 Token 中间件中,我确实使用了 AccountService,这里是 token 中间件:

public class TokenProviderMiddleware
{
    private readonly RequestDelegate _next;
    private readonly TokenProviderOptions _options;
    private readonly IAccountService _accountService;

    public TokenProviderMiddleware(RequestDelegate next, IOptions<TokenProviderOptions> options, IAccountService accountService)
    {
        _next = next;
        _options = options.Value;
        _accountService = accountService;
    }

    public Task Invoke(HttpContext context)
    {
        // If the request path doesn't match, skip
        if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
        {
            return _next(context);
        }

        if (!context.Request.Method.Equals("POST")
           || !context.Request.ContentType.Contains("application/json"))
        {
            context.Response.StatusCode = 400;
            return context.Response.WriteAsync("Bad request.");
        }

        return GenerateToken(context);
    }

    private async Task GenerateToken(HttpContext context)
    {
        var rawAccount = await new StreamReader(context.Request.Body).ReadToEndAsync();
        var authAccount = JsonConvert.DeserializeObject<AuthAccount>(rawAccount);

        var account = _accountService.GetAccountByEmailAndPassword(authAccount.EmailAddress, authAccount.Password);
        if (account == null)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Invalid email address or password.");
            return;
        }

        var now = DateTime.UtcNow;

        // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
        // You can add other claims here, if you want:
        var claims = new Claim[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, account.EmailAddress),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.Iat, ((DateTimeOffset)now).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
            new Claim(ClaimTypes.Role, account.RoleId.ToString()),
            new Claim(ClaimTypes.Name, account.EmailAddress)
        };

        // Create the JWT and write it to a string
        var jwt = new JwtSecurityToken(
            issuer: _options.Issuer,
            audience: _options.Audience,
            claims: claims,
            notBefore: now,
            expires: now.Add(_options.Expiration),
            signingCredentials: _options.SigningCredentials);
        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

        var response = new ApiResponse<AuthAccount>
        {
            StatusCode = (int)HttpStatusCode.OK,
            Message = "Access granted",
            Data = new AuthAccount
            {
                Access_Token = encodedJwt,
                Expires_In = (int)_options.Expiration.TotalSeconds
            }
        };

        // Serialize and return the response
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }));
    }
}

【问题讨论】:

  • 您在Configure(...) 类中调用的任何“时髦”代码,比如播种?发布您的配置方法。如果您在 Configure 中实例化 DbContext,这可能会导致麻烦,因为您在没有请求的地方解决它,因此没有范围。范围与 ASP.NET Core 中的请求相关联(没有真正绑定,但每个请求都会创建一个新范围)
  • 另外,看看stackoverflow.com/documentation/asp.net-core/1949/… 了解如何在 Configure 中正确实例化作用域服务可能是值得的
  • @Tseng 这篇文章有点长,但它的荣耀就在那里。
  • 但就您的观点而言,不,上下文或帐户服务没有什么时髦的。只是使用这些依赖项的中间件——这不应该引起问题吗?
  • 嗯,事情是:中间件只被实例化一次(一个单例),所以一切你.我看到您的 IAccountService 注入了中间件,所以这似乎是导致问题的原因。您必须在 Invoke 方法中根据上下文解决它,使用 context.RequestServices.GetRequiredServce&lt;T&gt;()

标签: c# dependency-injection asp.net-core asp.net-core-mvc entity-framework-core


【解决方案1】:

中间件只被实例化一次,所以它实际上是一个单例。

因此,您注入中间件构造函数的所有内容都从单例容器中解析(您可以通过 Configure 方法中的 app.ApplicationServices 访问该容器)。

我看到你的 IAccountService 被注入到中间件中,所以这似乎是导致问题的原因。您必须在 Invoke 方法中根据上下文解决它,使用

public Task Invoke(HttpContext context, IAccountService accountService)
{
    // If the request path doesn't match, skip
    if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
    {
        return _next(context);
    }

    if (!context.Request.Method.Equals("POST")
       || !context.Request.ContentType.Contains("application/json"))
    {
        context.Response.StatusCode = 400;
        return context.Response.WriteAsync("Bad request.");
    }

    return GenerateToken(context, accountService);
}

或

public Task Invoke(HttpContext context)
{
    var accountService = context.RequestServices.GetRequiredService<IAccountService>();

    // If the request path doesn't match, skip
    if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
    {
        return _next(context);
    }

    if (!context.Request.Method.Equals("POST")
       || !context.Request.ContentType.Contains("application/json"))
    {
        context.Response.StatusCode = 400;
        return context.Response.WriteAsync("Bad request.");
    }

    return GenerateToken(context, accountService);
}

【讨论】:

  • 是的,我会试试看是否有效,感谢您的帮助!
  • 对于其他尝试在 net Core 1.1 中使用 context.RequestServices.GetRequiredService&lt;...&gt;() 的人,您需要向 Microsoft.Extensions.DependancyInjection 添加一个 using
猜你喜欢
  • 2021-01-14
  • 1970-01-01
  • 2020-10-28
  • 2021-07-16
  • 2020-08-23
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
相关资源
最近更新 更多