Home > Back-end >  Can i Pass DbContext as interface or delegate
Can i Pass DbContext as interface or delegate

Time:03-30

I am having two dbcontext so want to pass it though some function so I can switch between the two dbcontext or I have to change in all the api controller

  public class AccountClassesController : ControllerBase
{
    private readonly  ApplicationDbContext _context;


    public AccountClassesController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: api/AccountClasses
    [HttpGet]
    public async Task<ActionResult<IEnumerable<AccountClass>>> GetAccountClass()
    {
        return await _context.AccountClass.ToListAsync();
    }

don't want to call the ApplicationDbContext from controller call it through some function or something

CodePudding user response:

You can check this answer here is it a good practice to pass an EF DbContext as delegate in services to attach all changes on it. But if you application don't have any performance issues is fine even if you instance new context due EF is incredible fast managing and building it up.

CodePudding user response:

Yes, you can create interfaces and modify your ApplicationDbContext to implement.

interface

public interface IAccountClass {
    Task<IEnumerable<AccountClass>> GetAccountClass();
}
public class AppDbContext: DbContext, IAccount {
   /* implementing interface
   */
  public Task<IEnumerable<AccountClass>> GetAccountClass() {
    return this.AccountClass.ToListAsync();
  }
}

Inject DbContext instance casting as interface in your controller:

   public AccountClassesController(IAccountClass accountClass)
    {
        _accountClass = accountClass;
    }

    // GET: api/AccountClasses
    [HttpGet]
    public async Task<ActionResult<IEnumerable<AccountClass>>> GetAccountClass()
    {
        return await this._accountClass.GetAccountClass();
    }

You must configure you dependency injection framework to inject a new ApplicationDbContext as IAccountClass.

  • Related