我想在我的自定义 AuthUserSession 中使用 Ormlite 进行简洁的数据库调用(顺便说一下,它位于与 AppHost 项目不同的项目中)。但我似乎只能得到原始数据库连接对象。
public class CustomUserSession : AuthUserSession
{
public string CustomProperty { get; set; }
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
base.OnAuthenticated(authService, session, tokens, authInfo);
// using (var Db = authService.TryResolve<ServiceStack.OrmLite.OrmLiteConnectionFactory>().OpenDbConnection())
using (var Db = authService.TryResolve<ServiceStack.OrmLite.IDbConnectionFactory>().OpenDbConnection())
{
// it seems I can make long winded calls to database using 'Db' but
// instead I want to eliminate this 'using statement' and simply do
// var result = Db.FirstOrDefault<MyTable>(x => x.Id == userId);
// CustomProperty = result.aStringField;
}
}
}
[旁注:文档经常说我们需要执行以下操作以将数据附加到会话,但我的会话对象似乎在没有它的情况下工作,即在派生的“服务”类中公开数据......我是否在某处错过了这一点?:]
//Important: You need to save the session!
authService.SaveSession(session, SessionExpiry);
// 更新*
我的 AppHost 有这个:
var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;
container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));
container.Register<IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));
var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>();
Gavin 的回答非常有帮助,但仍然无法给我提供 Ormlite 方法的“Db”对象。
我尝试创建
protected ServiceStack.OrmLite.IDbConnectionFactory Db1 { get; set; }
并使用以下行在 CustomUserSession() 构造函数中将其连接起来:
this.Db1 = EndpointHost.AppHost.TryResolve<ServiceStack.OrmLite.IDbConnectionFactory>();
但它没有按预期工作。