Passing ASP.NET User by Dependency Injection

一个人想着一个人 提交于 2019-12-10 17:13:39

问题


In my web application I have various components that need to access the currently authenticated user (HttpContext.User).

There are two obvious ways a component can access this: 1) Accessing getting the User from HttpContext.Current 2) Passing the user around in constructors

  1. Is not ideal because it makes testing difficult and ties application components to web concerns, when they really shouldn't know about it.
  2. Is just messy and complicates everything.

So I've been thinking about passing in the current user (or perhaps just the name/id) to any component that needs it using an IoC container (via dependency injection).

Is anyone using this technique to supply the current ASP.NET user to parts of the application? Or, Does this sound like a sensible approach? I would like know how this has worked out for people.

Thanks

UPDATE: Thanks to Raj for a great example. If anyone has a similar example using AutoFac it would be much appreciated!

UPDATE2: Thanks for the answers, wish I could have split the accept!


回答1:


In autofac:

builder.Register(c => HttpContext.Current.User.Identity).HttpRequestScoped();




回答2:


What about using the IPrincipal which also contains the IIdentity instead?

http://msdn.microsoft.com/en-us/library/f8kt7fb8%28v=VS.100%29.aspx

http://msdn.microsoft.com/en-us/library/f8kt7fb8%28v=VS.100%29.aspx

--updated--

private static void AddSecurityConcernsTo(IWindsorContainer container)
{
    container.Register(Component.For<IIdentity>()
      .LifeStyle.PerWebRequest
      .UsingFactoryMethod(() => HttpContext.Current.User.Identity));

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

    container.Register(Component.For<HttpSessionStateBase>()
        .LifeStyle.PerWebRequest
        .UsingFactoryMethod(() => new HttpSessionStateWrapper(HttpContext.Current.Session)));

}

ref: http://blog.coreycoogan.com/tag/controller-ioc/



来源:https://stackoverflow.com/questions/2824649/passing-asp-net-user-by-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!