2014-03-31 22 views
2

在另一個stackoverflow問題MVC5 IoC and Authentication第一個答案陳述作者使用依賴注入來注入IPrincipal。我希望爲我的彙編程序執行此操作,這樣我就不必從控制器中傳遞當前用戶(IPrincipal)。MVC5中的IPrincipal依賴注入

任何人都可以舉例說明如何使用DI在C#MVC5中注入IPrincipal?以下是我首先要實施的IoC。在給出第一個答案後添加。

public class ViewModelAssemblersInstaller : IWindsorInstaller 
    { 
     public void Install(IWindsorContainer container, IConfigurationStore store) 
     { 
      container.Register(
       Component.For<IAspNetUserAssembler>() 
       .ImplementedBy<AspNetUserAssembler>()); 
     } 
    } 

回答

4

對於溫莎城堡,它是這樣的:

container.Register(Component.For<IPrincipal>() 
    .LifeStyle.PerWebRequest 
    .UsingFactoryMethod(() => HttpContext.Current.User)); 
+0

謝謝馬克!順便說一句,您的個人資料中的圖書鏈接已損壞。 – Tom

+0

@Tom謝謝 - 我正在調查。 –

+0

只需注意User.Identity.GetUserId()方法是一種擴展方法,並且您必須包含以下用於訪問它的方法。 使用Microsoft.AspNet.Identity; – Tom

3

它去依賴你的IoC容器......對我來說,我使用的統一,並在我的容器註冊我能夠做到以下幾點:

container.RegisterType<IPrincipal>(new InjectionFactory(u => HttpContext.Current.User)); 

使用InjectionFactory ,unity將執行lambda返回構造函數注入時的當前HttpContext.Current.User。我還可以在我的非網絡應用程序中使用相同類型的註冊,而不是引用Thread.CurrentPrincipal

+1

我重新命名'u'爲'C',因爲它代表了'container' :) – abatishchev

+0

這看起來像偉大的信息,但我的項目是使用溫莎 – Tom