[英]Set CurrentPrincipal in an asynchronous login in WPF
我一直在網上搜索此內容,但找不到真正有效的解決方案。 情況如下:我有一個WPF應用程序,我想在其中向用戶顯示一個簡單的登錄表單。 嘗試使用MVVM,因此我在登錄命令后有一個LoginViewModel,其中包含以下代碼:
try
{
WithClient(servfact.GetServiceClient<IAccountService>(), proxy =>
{
principal = proxy.AuthenticateUser(Login, password);
});
Thread.CurrentPrincipal = principal;
}
catch(...) { ... }
“ WithClient”是我的viewmodel基類中的一種簡短方法,可用於實例化和處理我的服務代理:
protected void WithClient<T>(T proxy, Action<T> codeToExecute)
{
try { codeToExecute(proxy); }
finally
{
IDisposable toDispose = (proxy as IDisposable);
if(toDispose != null) { toDispose.Dispose(); }
}
}
現在,我的大多數服務都是異步的,並且正在進行WithClient的異步變體,它也可以正常工作:
protected async Task WithClientAsync<T>(T proxy, Func<T, Task> codeToExecute)
{
try { await codeToExecute(proxy); }
finally
{
IDisposable toDispose = (proxy as IDisposable);
if(toDispose != null) { toDispose.Dispose(); }
}
}
每當我也想異步登錄時,麻煩就開始了。 顯然,我不希望UI在登錄時凍結(或為此訪問任何WCF服務)。 這樣做本身可以很好地工作,但是問題出在我設置CurrentPrincipal的那段代碼中。 這個問題可能是大多數人都熟悉的:它似乎設置得很好。 然后,在我的程序中,我想使用CurrentPrincipal(在客戶端或將用戶登錄名發送到消息頭中的WCF服務),但似乎已重置為標准GenericPrincipal。 當我將登錄恢復為同步狀態時,CurrentPrincipal很好。 簡而言之:如何在異步代碼中設置主體,讓它在以后繼續存在,而不是恢復為標准主體?
好吧,好吧,一年沒有答案。 不用擔心,因為我設法自己解決了這個問題:我只是將所有內容包裹在一個單例中:
public sealed class CurrentPrincipalFacade : IPrincipal
{
#region Singleton mechanism
private static readonly CurrentPrincipalFacade instance = new CurrentPrincipalFacade();
public static CurrentPrincipalFacade Instance { get { return instance; } }
private CurrentPrincipalFacade() { }
#endregion
#region IPrincipal members
public IPrincipal Principal { get; set; }
public IIdentity Identity { get { return Principal == null ? null : Principal.Identity; } }
public bool IsInRole(string role) { return Principal != null && Principal.IsInRole(role); }
public void Reset() { Principal = new GenericPrincipal(new GenericIdentity(""), new string[] { }); }
#endregion}
因此,我在登錄后進行了設置。 我想問題是我在另一個線程中設置了主體,而當我退出該線程時卻迷失了?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.