2014-04-03 40 views
6

我有一個使用Structuremap 2.x版本的最新版本的現有應用程序,它工作正常。 StructureMap 3最近剛剛投入使用,我決定試着更新它,看看它是如何發展的。使用StructureMap3在MVC應用程序中依賴注入當前用戶

但無論我做什麼,我似乎無法得到它正確解決當前用戶。我不知道它是否試圖在應用程序的生命週期中過早地構建依賴關係,或者交易可能是什麼。由於最近的發佈,幾乎沒有任何信息可以用於我的發現。

註冊依賴關係的行。

For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current)); 
For<ICurrentUser>().HybridHttpOrThreadLocalScoped().Use(x => GetCurrentUser(x)); 

我的方法來解決依賴

private ICurrentUser GetCurrentUser(IContext context) 
    { 
     try 
     { 
      var httpContext = context.GetInstance<HttpContextBase>(); 
      if (httpContext == null) return null; 
      if (httpContext.User == null) return null; 
      var user = httpContext.User; 
      if (!user.Identity.IsAuthenticated) return null; 

      var personId = user.GetIdentityId().GetValueOrDefault(); 
      return new CurrentUser(personId, user.Identity.Name); 
     } 
     catch (Exception ex) 
     { 
      context.GetInstance<ILogger>().Error("Error trying to determine the current user.", ex); 
      throw new Exception("Error trying to determine the current user.", ex); 
     } 
    } 

我ICurrentUser接口

public interface ICurrentUser 
{ 
    Guid UserId { get; } 
    string UserName { get; } 
} 

的排隊叫號GetIdentityId()基本上只是一個擴展方法包裝邏輯檢查存儲在用戶標識作爲ClaimTypes.NameIdentifier類型的索賠項目的身份,處理空值併合併到Guid等。

有沒有其他人嘗試在webapp中使用StructureMap3來完成這樣的事情?

回答

1

自己遇到這個問題後,似乎每個在StructureMap中相關的Web都被移動到一個單獨的Nuget包中,名爲StructureMap.Web,可能是found here

我認爲這是因爲StructureMap 3現在是兼容PLC(Portalble Class Library)的,所以把它移動到一個單獨的包中是有道理的。

一旦包含該軟件包,一切都應該繼續正常工作。

+0

我也看到了,但這是安裝了新的StructureMap.Web軟件包。當我有時間再試一次時,我會再看一次。 –