Home > Software design >  How do I get a DBContext for my API filter? (To access the DB)
How do I get a DBContext for my API filter? (To access the DB)

Time:04-25

I have a filter in my API (for Auth), but in order to check the tokens I have to look in my database, which is not hard but when I want to get my DataBaseContext through my ctor I can't use the filter anymore. See here:

This here is a piece of the filter class:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiAuth : Attribute, IAsyncActionFilter
{
    private readonly DataBaseContext _db;

    public ApiAuth(DataBaseContext db)
        => _db = db;

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
    }

This is a piece of the User Controller

[Route("api/v1/[controller]")]
[ApiController]
[ApiAuth]
public class UserController : Controller
{
}

The "[ApiAuth]" now gives me an error that it expects a DataBaseContext, which it cannot give it.

Error "CS7036: No argument was given that matches the formal parameter "db" of "ApiAuth.ApiAuth(Databasecontext)"."

My problem is, I don't know how else to get my context, you can only get it through the ctor, or am I wrong?

CodePudding user response:

Couple of things to check here.

  1. Did you register dbcontext in ConfigureServices method of startup class?

like this

services.AddDbContext<YourDBContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  1. Did you register the filter either globally / or as a service in the IoC container in ConfigureServices?

with this settings you should get dbcontext there in your filter.

Otherwise you can use service locator pattern to resolve the dbcontext which does not require constructor injection.

var context = context.HttpContext.RequestServices.GetService<DataBaseContext>();

also your filter should be applied like this

[ServiceFilter(typeof(ApiAuth))]

  • Related