如何在Web API 2自托管应用中通过Unity注册IAuthenticationManager

本文关键字:应用 Unity IAuthenticationManager 注册 Web API | 更新日期: 2023-09-27 18:15:31

我希望我的Web API应用程序通过ASP登录用户。净的身份。在我的AuthController中,我做了以下操作:

//...getting claimsIdentity etc...

_authenticationManager.SignIn(claimsIdentity)

其中_authenticationManagerIAuthenticationManager的实例

我使用Unity,所以IAuthenticationManager以以下方式注册:

container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));

这适用于托管在IIS中的应用程序。但是我也有一些在自托管环境上运行的集成测试,问题是IAuthenticationManager解析失败,因为HttpContext.Current为空。

是否有任何方法注册IAuthenticationManager实现并在自托管和IIS中使用它?我还希望能够在单元测试中通过控制器的构造函数注入此依赖项。

如何在Web API 2自托管应用中通过Unity注册IAuthenticationManager

尝试在统一中添加下一行。配置:

container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));