2014-03-31 23 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