如何制定正确的ApplicationDbContext生命周期

问题描述 投票:0回答:1

当我执行一个方法时,在发出外部 HttpClient 请求后,我的

ApplicationDbContext
生命周期结束了,如何使这个方法正确?

方法

    public async Task ConfirmEmail(int userId, Guid codeFromUser)
    {
        var user = _accountAccessor.GetUserById(userId);
        
        if (user.EmailConfirmed) throw new BadRequestException("Email already verified");

        // Getting Confirmation Code        
        var confirmationCode = await ResponseHelper.GetResponseAsync(_httpClientFactory, $"{ServiceUrlVariables.ConfirmationCodeApi}/GetCodeByUserId/{userId}");
        var confirmationCodeDto = await ResponseHelper.DeserializeResponseAsync<ConfirmationCodeDto>(confirmationCode);

        // validation
        if (confirmationCodeDto.ExpiresAt < DateTime.UtcNow) throw new BadRequestException("Code expired");
        if (confirmationCodeDto.Code != codeFromUser) throw new BadRequestException("Your code is wrong");
        
        // setting `EmailConfirmed == true`
        user.EmailConfirmed = true;
        _accountAccessor.UpdateUser(user);

        var codeId = confirmationCodeDto.Id;
        // Deleting ConfirmationCode from Db, cuz it's already verified
        await ResponseHelper.DeleteResponseAsync(_httpClientFactory, $"{ServiceUrlVariables.ConfirmationCodeApi}/DeleteConfirmationCodeById/{codeId}");
    }

响应助手

    public static async Task<HttpResponseMessage> GetResponseAsync(IHttpClientFactory httpClientFactory, string requestUri)
    {
        using var client = httpClientFactory.CreateClient();
        var response = await client.GetAsync(requestUri).ConfigureAwait(false);
        
        response.EnsureSuccessStatusCode();
        
        return response;
    }

节目

builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(
    ConnectionStringsVariables.BookShopDB
));

我是新手,对我来说有点难以理解如何修复此类错误。

如果我的理解是正确的,异步请求的寿命超出了我的 dbcontext 的范围

asp.net .net microservices
1个回答
0
投票

嗯,你可以做这样的事情,取决于哪种生命周期更适合你的环境:

services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseNpgsql(ConnectionStringsVariables.BookShopDB);
            
        }, contextLifetime: ServiceLifetime.Transient, optionsLifetime: ServiceLifetime.Transient);

了解更多信息:https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/

如果您想了解其中每一项的工作原理,请查看此处: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-8.0

如果我没有回答正确,很乐意回答其他问题:)

© www.soinside.com 2019 - 2024. All rights reserved.