I have this snippet of code --
public class UserManager : UserManager<ApplicationUser>
{
private ApplicationDbContext _dbAccess;
public UserManager() :
base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
{
this.UserValidator = new CustomUserValidator<ApplicationUser>(this);
var provider = new MachineKeyProtectionProvider();
this.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(
provider.Create("SomeCoolAuthentication"));
//DO I REALLY NEED TO DO THIS AGAIN?
this._dbAccess = new ApplicationDBContext();
}
public bool myOwnHelperMethod(){
//is there a way to use the ApplicationDbContext instance that
//was initialized in the base constructor here?
//Or do i have to create a new instance?
}
}
Is there a better way to write this so that I can instantiate the ApplicationDBContext, use it to call the base constructor, and then use the same instance later in some helper methods? Or do I have to create another instance in the constructor for use in the helper methods.
You have a couple of options.
The first would be to use dependency injection. With this approach, you would remove the creation of ApplicationDbContext
to outside of UserManager
and pass it in through the constructor. e.g.:
public class UserManager : UserManager<ApplicationUser>
{
private ApplicationDbContext _dbAccess;
public UserManager(ApplicationDbContext dbAccess) :
base(new UserStore<ApplicationUser>(dbAccess))
{
...
this._dbAccess = dbAccess;
}
...
}
The second option I was just about to suggest has been provided by @Juan in his answer, so I won't repeat that here.