I am creating a custom ASP store and here is the problem presented as so: Invitation Manager class:
public InvitationManager(InvitationStore store)
{
Store = store ?? throw new ArgumentNullException(nameof(store));
UserManager = Context.GetOwinContext().Get<ApplicationUserManager>();
}
public async void SendInvitation(Invitation inv, ApplicationUser SentTo)
{
var SentToUser = await UserManager.FindByIdAsync(SentTo.Id);
inv.SentTo = SentToUser;
var SentBy = await UserManager.FindByNameAsync(Context.User.Identity.Name);
inv.SentBy = SentBy.Id;
var not = new Notification(Referenced_user: SentTo);
inv.AssociatedNotification = not;
SentToUser.Notifications.Add(not);
await Store.CreateAsync(inv);
}
public IQueryable<Invitation> Invitations
{
get
{
var queryableStore = Store.Invitations;
if (queryableStore == null)
{
throw new NotSupportedException("Can't access database invitations");
}
return queryableStore;
}
}
protected HttpContext Context
{
get
{
return HttpContext.Current;
}
}
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
if(_userManager == null)
{
_userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
}
return _userManager;
}
set
{
_userManager = value;
}
}
The application says that the dbcontext has disposed and I can't use it anymore. Moreover after some research I found out that I am maybe using different contexts for the same request which is this one who causes problems:
var SentBy = await UserManager.FindByNameAsync(Context.User.Identity.Name);
So how can I fix that? How to make them retrieve from the same context?
Still here is how is stored the dbcontext and it's relation with the UserManager :
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
reurn new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
}
And i did exactly the same procedure for my Invitation Store i take the DbContext from the OwinContext wich has been declared at the application Startup.Auth.cs File. Wich get retrieved each time a user make an HTTP request.