【发布时间】:2013-11-17 04:36:08
【问题描述】:
我正在尝试创建一个 CustomAuthUserSession,同时使用 RefIdStr 属性将我自己的用户文档与 UserAuth 对象相关联。
在我的 CustomUserAuthSession 的 OnAuthenticated 方法中,我正在执行以下操作
- 通过会话上的 UserAuthId 获取 userAuth 对象
- 为 Raven 创建 IDocumentSession 实例
- 创建一个新的用户实例并在我的文档会话中调用 Store
- 在 userAuth 上更新 RefIdStr
- 在我的 userauth 存储库中调用 SaveUserAuth
方法如下
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
base.OnAuthenticated(authService, session, tokens, authInfo);
var documentSession = authService.TryResolve<IDocumentSession>();
//get userAuth from raven
//var userAuth = documentSession.Load<UserAuth>(session.UserAuthId); //should this work?
var userAuthRepo = authService.ResolveService<IUserAuthRepository>();
var userAuth = userAuthRepo.GetUserAuth(session.UserAuthId);
if (userAuth.RefIdStr == null)
{
//need to create new User and save to Raven
var newUser = new User()
{
UserName = session.UserName,
Email = session.Email,
//Other properties...
};
documentSession.Store(newUser);
this.UserID = newUser.Id; //UserId property on custom session
userAuth.RefIdStr = newUser.Id;
userAuthRepo.SaveUserAuth(userAuth); //getting error here...
}
else
{
//get User from raven
var user = documentSession.Load<User>(userAuth.RefIdStr);
this.UserID = user.Id;
}
}
当我使用 SaveUserAuth 方法时,我收到以下错误...
Attempted to associate a different object with id 'UserAuths/12345'.
这是我设置文档存储和 IOC 的方式...
//Set up RavenDB
var ravenStore = new DocumentStore()
{
ConnectionStringName = "RavenDB"
}.Initialize();
IndexCreation.CreateIndexes(typeof(RavenUserAuthRepository).Assembly, ravenStore);
container.Register(ravenStore);
container.Register(c => c.Resolve<IDocumentStore>().OpenSession()).ReusedWithin(ReuseScope.Request);
以及我如何配置我的 auth repo....
//register auth repository
container.Register<IUserAuthRepository>(p => new RavenUserAuthRepository(p.Resolve<IDocumentStore>(), p.Resolve<IDocumentSession>()));
var authRepo = (RavenUserAuthRepository)container.Resolve<IUserAuthRepository>();
任何想法为什么会发生此错误?
编辑
澄清一下……我的意图是让它以与 socialbootstrapapi 项目类似的方式工作。
编辑 2
根据下面的 cmets,我已将 IUserAuthRepository 的 Funq 注册更改为:
container.Register<IUserAuthRepository>(p => new RavenUserAuthRepository(p.Resolve<IDocumentStore>(), p.Resolve<IDocumentSession>())).ReusedWithin(ReuseScope.Request);
但我仍然遇到同样的错误......
【问题讨论】:
-
有什么想法吗?也许@mythz 会告诉我我搞砸了什么:/
-
这对我来说听起来像是一个 DocumentSession 问题。如果您解析 DocumentStore 并为您的工作创建一个新会话,而不是从 IOC 中解析 DocumentSession,会发生什么?
-
我相信这绝对是一个文档会话问题,因为 Raven AuthRepository 正在为每个调用创建新会话(不是由从文档存储创建的 IOC 注入的)。我只想为每个请求创建一个文档会话。这就是我卡住的地方。不确定访问和更新 UserAuth 对象的正确方法是什么。我以为我应该使用 IAuthRepository,但它导致了这个文档会话问题。
-
我在这里在黑暗中开枪,但我认为您的 IUserAuthRepository 已注册为单例,因此它可能会重用同一个文档会话。
-
是的,您正在查看的示例可能正在使用使用 IDbConnectionFactory 构造的存储库。可以注册为单例,因为它会创建新的连接。 RavenUserAuthRepository 没有。它使用您传入的 IDocumentSession。因此,即使您在 RequestScope 中创建了 IDocumentSession,RavenUserAuthRepository 也已创建为单例,并挂在用于构造它的初始文档会话上。
标签: c# .net nosql servicestack ravendb