【问题标题】:asp.net identity 2.1 injecting IAuthenticationManager using StructureMapasp.net identity 2.1 使用 StructureMap 注入 IAuthenticationManager
【发布时间】:2014-10-22 02:37:08
【问题描述】:

谁能指点我一些示例的方向或如何实现这一点的说明?

【问题讨论】:

标签: asp.net-mvc-5 structuremap asp.net-identity-2


【解决方案1】:

我没有使用过 StructureMap,但我使用 Autofac 和 SimpleInjector 完成了这项工作。

Autofac 注册如下所示:

builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).As<IAuthenticationManager>();

SimpleInjector 中的注册如下所示:

container.RegisterPerWebRequest(() => HttpContext.Current.GetOwinContext().Authentication);

通过查看 StructureMap 教程,我可以猜到注册会是这样的:

ForRequestedType<IAuthenticationManager>()
    .TheDefaultIs(() => HttpContext.Current.GetOwinContext().Authentication)

【讨论】:

  • 这是我原以为会的,但由于 HttpContext.Current.GetOwinContext().Authentication 为空,它会引发错误。
  • 这意味着您在为请求创建 OwinContext 之前尝试解析 IAuthenticationManager。通常,当您尝试在没有 http-request 的情况下解决它时会发生这种情况,即在 Global.asax
  • 这就是问题所在,我应该在哪里做这个?
  • 为什么在请求发生之前需要IAuthenticationManager
  • StructureMap 也有可能在注册时创建所有实例并尝试同时解析IAuthManager。尝试做后期解决。类似这样的答案:stackoverflow.com/a/6567855/809357
【解决方案2】:

这最初是通过将 Identity 转换为使用 int 作为唯一键值来实现的,如 here 所述。

然后我扩展了它并使用 IAuthenticationManager 创建了一个自定义 AuthenticationManager。

然后我设置 StructureMap 如下:

For<IAuthenticationManager>()
    .Use<MyAuthenticationManager>(
     () => new MyAuthenticationManager(HttpContext.Current.GetOwinContext().Authentication));

感谢@trailmax

【讨论】:

  • 不错的解决方案。装饰的胜利!
猜你喜欢
  • 2015-01-12
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
相关资源
最近更新 更多