'how do i instantiate dbcontext in a customFilterAttribute class WITHOUT constructor injection in .Net6

in my program.cs file i have the DB service setup as

builder.Services.AddDbContext<ADbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("ADevDB"));
});

and under the DatabaseConetxt class i have

public class ADbContext : DbContext
{
    public ADbContext(DbContextOptions<ADbContext> options) : base(options)
    {



    }
}

i am trying to access EFCore in a custom filter class without constructor injection. this is because when i apply the [CustomFilter] on an action i don't want it to request that an argument needs to be passed to the customFilter Constructor for DBConetext



Solution 1:[1]

var connectionstring = "Connection string";

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
    optionsBuilder.UseSqlServer(connectionstring);


ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options);

// Or you can also instantiate inside using

using(ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options))
{
   //...do stuff
}

Check on this question too for various answers

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MKougiouris