2013-07-11 32 views
5

我很努力地找到正確的方法將UserAuthSession對象(從ServiceStack的AuthUserSession派生)的當前實例注入我的數據訪問存儲庫,以便它們自動更新插入/更新/刪除操作中的更改跟蹤字段。如何將ServiceStack AuthSession注入到我的存儲庫類中?

如果我在我的服務代碼newing機庫這將是一個沒有腦子,我只想做:

var repo = new MyRepository(SessionAs<UserAuthSession>()); 

然而,我的版本庫自動有線(注入)的服務,所以UserAuthSession必須從某處存儲庫與IOC容器的註冊規定的拉姆達抓起,如:

public class AppHost : AppHostBase 
{ 
    public override void Configure(Container container) 
    { 
     container.Register<ICacheClient>(new MemoryCacheClient()); 
     container.Register<IRepository>(c => 
     { 
      return new MyRepository(**?????**); <-- resolve and pass UserAuthSession 
     } 
    } 
} 

現在,看着爲Service類ServiceStack代碼:

private object userSession; 
    protected virtual TUserSession SessionAs<TUserSession>() 
    { 
     if (userSession == null) 
     { 
      userSession = TryResolve<TUserSession>(); //Easier to mock 
      if (userSession == null) 
       userSession = Cache.SessionAs<TUserSession>(Request, Response); 
     } 
     return (TUserSession)userSession; 
    } 

我可以看到,它查找基於當前RequestResponse緩存的會議,但這些都沒有提供給我的拉姆達。

解決方案是什麼?還是我從一個完全錯誤的角度來處理這個問題?

+0

忘了提,我在測試中使用'JsonServiceClient'我的代碼,而不是通過直接調用服務方法。所以我期待'HttpContext.Current'在lambda中可用,但它始終爲空。 –

回答

6

another StackOverflow post中找到答案,它將請求構建的會話存儲在請求/線程範圍Items字典ServiceStack.Common.HostContext的字典中。 。

AppHost.Configure()現在有下面的代碼:

// Add a request filter storing the current session in HostContext to be 
// accessible from anywhere within the scope of the current request. 
RequestFilters.Add((httpReq, httpRes, requestDTO) => 
{ 
    var session = httpReq.GetSession(); 
    HostContext.Instance.Items.Add(Constants.UserSessionKey, session); 
}); 

// Make UserAuthSession resolvable from HostContext.Instance.Items. 
container.Register<UserAuthSession>(c => 
{ 
    return HostContext.Instance.Items[Constants.UserSessionKey] as UserAuthSession; 
}); 

// Wire up the repository. 
container.Register<IRepository>(c => 
{ 
    return new MyRepository(c.Resolve<UserAuthSession>()); 
}); 
+0

太棒了,但你如何將事情存回會議? – fractal

+0

我不在乎保存任何東西回到會話中,在我的情況下,只有當我的回購需要知道即將修改數據的用戶的身份時,這是一條單行道。 –

相關問題