在 ASP.Net 核心中使用上下文注入时出现 InvalidOperationException

InvalidOperationException When using Context Injection in ASP.Net Core

在我的 ASP.Net 核心网络应用程序中,我在启动时使用以下命令连接到我的数据库

services.AddDbContext<TimeSheetContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("AzureSql")));

在我尝试对我的 DBcontext class.

进行注入之前,它工作正常

我有一个接口和 class 获取登录用户

public interface IGetUserProvider
{
    string UserName {get; }
    int BranchID {get; }
}

public class GetUserProvider : IGetUserProvider
{
    public string UserName { get; set; }
    public int BranchID { get; set; }    

    public GetUserProvider(IHttpContextAccessor accessor)
    {
        
        UserName = accessor.HttpContext?.User.Claims.SingleOrDefault(x => x.Type == UserName)?.Value;
        BranchID = 6108;
    }    
}

BranchID = 6108 将根据用户名动态设置,但为了调试我自己设置。

当我在程序中有这些 class 时,每当我 select Web 应用程序上的 Razor 页面时,它都会抛出错误

InvalidOperationException: A named connection string was used, but the name 'AzureSql' was not found in the application's configuration.

在 Razor 代码隐藏中调用上下文时发生异常,例如

public async Task OnGetAsync()
        {
            BranchHour = await _context.BranchHours
                .Include(b => b.Branch)
                .Where(d => d.BranchOpen.Date == DateTime.Today.Date)
                .OrderBy(b => b.Branch.BranchNumber)
                .ToListAsync();
        }

正如我所说,代码在没有注入的情况下运行良好,但当它在其中时,它声称没有名为 AzureSql 的连接字符串,而显然存在。我不得不假设错误是由其他原因引起的,但我似乎找不到它。

使用数据库上下文编辑

public TimeSheetContext(DbContextOptions<TimeSheetContext> options, IGetUserProvider userProvider)
            : base(options)
        {
            User = userProvider.UserName;
            branchFilter = userProvider.BranchID;
            
        }

注入的原因是为了在OnModelCreating内部用作全局过滤器

modelBuilder.Entity<Branch>().HasQueryFilter(b => b.ContractorCode == branchFilter);

通过删除上下文中的空白构造函数解决了这个问题。所有功劳都归功于评论中的 Ivan。