0

I don't quite understand how this dependency injection works. I have a Web API that uses a DBContext, and it is working on everything except for when I need to call a new instance of a class. It works on my controllers and it works when I call a class via hangfire (just not a new instance without hangfire). I tried passing the _context from my controller to the instance of the class I need to call, but the context was null there so that must not be how it is done. How can I call a new instance of PowerRun and use the dbcontext in it? Do I need to create a new instance of the PowerSourceDbContext, and if so what options to I specify?

    private static PowerSourceDbContext _context;
    private static PowerRun PowerRun = new PowerRun(_context);
    public ForwardController(PowerSourceDbContext context)
    {
        _context = context;
    }

public class PowerRun
{

    private static PowerSourceDbContext? powersource;
    public PowerRun(PowerSourceDbContext context)
    {
        powersource = context;
    }

public class PowerSourceDbContext : DbContext
{

    public PowerSourceDbContext(DbContextOptions<PowerSourceDbContext> options) : base(options)
    {

    }

    public DbSet<MailboxUser> MailboxUsers => Set<MailboxUser>();
    public DbSet<MailContact> MailContacts => Set<MailContact>();
    public DbSet<MailGroup> MailGroups => Set<MailGroup>();
    public DbSet<ScheduledForward> ScheduledForwards => Set<ScheduledForward>();

}

For Example, when I call with Hangfire I don't need to specify anything for the dbcontext (it just works). So how is hangfire calling this?

var result = BackgroundJob.ContinueJobWith<PowerRun>(jobId, x => x.UpdateDatabaseAsync());
Tom Gordon
  • 435
  • 4
  • 15
  • Does this answer your question? [Use DbContext in ASP .Net Singleton Injected Class](https://stackoverflow.com/questions/36332239/use-dbcontext-in-asp-net-singleton-injected-class) – Jeremy Lakeman Feb 28 '23 at 00:43
  • Why are you creating a new instance of PowerRun yourself? Why not let your DI container create an instance for you? The unwritten rule of Dependency Injection in C# is to avoid invoking the "new" keyword for anything but "dummy" classes that just contain data. – mason Feb 28 '23 at 00:55

1 Answers1

0

The problem is where you are creating the new instance. When creating the PowerRun instance, you are passing the _context variable when it has not been initialized yet.

You will need to change you controller constructor to this:

private static PowerSourceDbContext _context;
private static PowerRun powerRun;

public ForwardController(PowerSourceDbContext context) {
  _context = context;
  powerRun = new PowerRun(_context);
}
Luis
  • 866
  • 4
  • 7