I am having trouble calling my class when trying to use the database in the class. I have my context setup as so
public class AppDbContext : DbContext
{
public DbSet<User> Users {get; set;}
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{ }
}
I try to access my database in the class using this method
private AppDbContext db;
public PasswordManager(AppDbContext db)
{
this.db = db;
}
The problem that I'm running into is when I try to use that class and do something like new PasswordManager()
it wants a parameter sent for the db in the constructor. What am I doing wrong? I don't want to pass the database as a parameter, but I need to use the database in the class for data. Should I be using a using
statement instead when in a class?
When you use dependency injection, you must use dependency injection all the way. That means not using
new
directly. In order to inject the dependencies, the DI container must be responsible for instantiating it. If you instantiate it, then nothing will be injected.Long and short, you need to register
PasswordManager
with the service collection (if you haven't already) and then injectPasswordManager
into wherever you're using it, rather than newing it up yourself.