我正在创建一个自定义 ASP 商店,问题如下: 邀请经理类:
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;
}
}
应用程序说 dbcontext 已释放,我无法再使用它。此外,经过一些研究,我发现我可能对同一个请求使用不同的上下文,这就是导致问题的原因:
var SentBy = await UserManager.FindByNameAsync(Context.User.Identity.Name);
那么我该如何解决这个问题呢?如何让它们从相同的上下文中检索?
这里还是 dbcontext 的存储方式以及它与 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>()));
}
我对邀请存储执行了完全相同的过程,我从已在应用程序 Startup.Auth.cs 文件中声明的 OwinContext 中获取 DbContext。每次用户发出 HTTP 请求时都会检索到它。