I'm trying to get the DbContext from the current Owin context, so I can use a single context on my application, however, I'm getting a NullReferenceException.
I can access UserManager and RoleManager:
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
They're configured how they came by default in the Identity sample project:
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
But trying to get the context to use it directly:
ApplicationDbContext context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
It always returns null on my controller. How can I get the current DbContext from the Owin context?
EDIT:
I was creating a new context to use with my generic repository
public AdminController()
{
AppContext = new ApplicationDbContext();
this.repoProyects = new GenericRepository<Proyect>(AppContext);
}
But it was creating a problem with entities being referenced from multiple contexts, so I'm trying to get the current Owin context like this:
public AdminController()
{
this.AppContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
this.repoProyects = new GenericRepository<Proyect>(AppContext);
}
HttpContext is always null from here, so I don't know how to get the context to pass it to my class.
I was missing the initialization of my entities in the Startup method ConfigureOauth...
app.CreatePerOwinContext<OwinAuthDbContext>(() => new OwinAuthDbContext());
Found the answer here: http://www.c-sharpcorner.com/UploadFile/ff2f08/token-based-authentication-using-Asp-Net-web-api-owin-and-i/