Tom*_*Tom 2 c# authentication dependency-injection asp.net-mvc-5
在另一个stackoverflow问题MVC5 IoC和Authentication中,第一个答案表明作者使用依赖注入来注入IPrincipal.我很乐意为我的汇编程序执行此操作,以便我不必从控制器传递当前用户(IPrincipal).
任何人都可以举例说明如何使用DI在C#MVC5中注入IPrincipal?下面是我首先要实现的IoC.在给出第一个答案后添加.
public class ViewModelAssemblersInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<IAspNetUserAssembler>()
.ImplementedBy<AspNetUserAssembler>());
}
}
Run Code Online (Sandbox Code Playgroud)
对于温莎城堡,它是这样的:
container.Register(Component.For<IPrincipal>()
.LifeStyle.PerWebRequest
.UsingFactoryMethod(() => HttpContext.Current.User));
Run Code Online (Sandbox Code Playgroud)
它取决于您的IoC容器...对我来说,我使用Unity,在我的容器注册中,我可以执行以下操作:
container.RegisterType<IPrincipal>(new InjectionFactory(u => HttpContext.Current.User));
Run Code Online (Sandbox Code Playgroud)
使用InjectionFactory,unity将执行lambda返回HttpContext.Current.User构造函数注入时的当前值。我还可以在非Web应用程序中使用相同类型的注册,而不必引用Thread.CurrentPrincipal。
| 归档时间: |
|
| 查看次数: |
1976 次 |
| 最近记录: |