简体   繁体   中英

InvalidOperationException When using Context Injection in ASP.Net Core

In my ASP.Net core web app, I connect to my DB using the following in startup

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

This works fine until I attempt injection on my DBcontext class.

I have an interface and class that gets the logged in user

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 will be dynamic based on UserName but for debugging I am setting it myself.

When I have these classes in the program, whenever I select a Razor Page on the web app it throws the error

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

The exception is occurring at the point the context is called in the Razor Code Behind eg

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();
        }

As I say, the code runs fine without the Injection but when it is in it claims there is no connection string called AzureSql when obviously there is. I have to assume the error is being caused by something else but I can't seem to find it.

Edit with DB Context

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

The reason for the injection is to be used as a global filter inside OnModelCreating

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

This was solved by removing the blank constructor I had in the context. All credit goes to Ivan in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM